python 文件操作

路径操作:

__file__  # 获取执行文件的位置,返回可能是绝对路径或相对路径。
os.path.abspath("./")  # 返回绝对路径
os.path.join(os.path.abspath("./"), "test.txt") # 拼接路径
os.path.dirname(path) # 去掉文件名,返回目录
os.listdir(os.path.abspath("./")) # 获取目录下所有文件和目录名,返回一个数组
os.makedirs(path)  # 创建文件
os.makedirs(path) # 多层创建目录
os.mkdir(path) # 创建目录

  

获取当前文件的路径:

os.path.dirname(__file__) 
os.path.abspath("./")  

获取当前文件上两层路径:

os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

 

判断*是否存在,返回的是bool类型:

os.path.isdir()  # 是否是一个目录
os.path.isfile() # 是否是一个文件
os.path.exists() # 文件/目录是否存在

 

查找目录*下文件名所有包含“.py”的文件:

def get_file(dir):
    for child_dir in os.listdir(os.path.abspath(dir)):
        cur_dir = os.path.join(os.path.abspath(dir), child_dir)
        if ".py" in child_dir:
            print(child_dir)
        elif os.path.isdir(cur_dir):
            get_file(cur_dir)

 

posted @ 2019-08-05 23:36  caizhanjin  阅读(118)  评论(0)    收藏  举报