python目录及文件操作

 版权声明:本文为博主原创文章,欢迎转载,并请注明出处。联系方式:[email protected]

 一、分离路径

fpath,fname=os.path.split(r'E:\projects\abc\def.png')

'E:\\projects\\abc', 'def.png'

扩展名

os.path.split(r'E:\projects\abc\def.png')[-1].split('.')[-1]

png

fpath,fname=os.path.split(r'E:\projects\abc')

'E:\\projects', 'abc'

二、合成路径

pa = os.path.join(r'E:\projects\abc', 'def.png')

E:\\projects\\abc\\def.png

pa = os.path.join(r'E:\projects', 'abc', 'def.png')

E:\\projects\\abc\\def.png

 三、判断目录/文件是否存在

os.path.exists()

四、目录创建

os.makedirs(fpath) # 可以一直创建各级目录
os.mkdir(fpath) # 只能创建最后一级目录

五、目录删除

shutil.rmtree(fpath)  #可以删除非空目录

os.rmdir(path)  # 目录非空时才能被删除

六、列出目录下的子目录和文件

os.listdir(r'E:\projects')  

七、列出目录下的子目录

[f for f in os.listdir(file_path) if os.path.isdir(os.path.join(file_path, f))]  #  只有一级目录名

[os.path.join(file_path, f) for f in os.listdir(file_path) if os.path.isdir(os.path.join(file_path, f))]  #  全路径

八、列出目录下的文件

[f for f in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, f))]  #  只有文件名

[os.path.join(file_path, f) for f in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, f))]  #  文件绝对路径

九、删除文件

os.remove()

十、列出目录下的所有子目录

path = r'E:\soft'
for dirpath, dirnames, filenames in os.walk(path):
    for dirname in dirnames:
        print(os.path.join(dirpath, dirname))

十一、列出目录下的所有文件

path = r'E:\soft'
for dirpath, dirnames, filenames in os.walk(path):
    for filename in filenames:
        print(os.path.join(dirpath, filename))

十二、遍历目录

path = r'E:\soft'
for dirpath, dirnames, filenames in os.walk(path):
    print(dirpath, dirnames, filenames)

猜你喜欢

转载自www.cnblogs.com/zhengbiqing/p/11072820.html