Python 常用文件操作(文件创建、遍历、移动、更改后缀名等)
1、判断文件夹是否存在,不存在则创建:
import os
if not os.path.exists(path):
os.mkdir(path)
2、遍历文件夹中有特定格式的文件:
import os
import fnmatch
img_list = fnmatch.filter(os.listdir(path), '*.png')
for img in img_list :
……
3、重命名文件:
import os
os.rename(Old_Dir,New_Dir)
4、路径连接:
import os
New_Dir=os.path.join(path,filestr,filetype)
5、复制文件:
import shutil
shutil.copy(Old_Dir, New_Dir)
6、替换后缀名:
jpg_img=files[:-4]+".jpg"
7、替换路径中字符:
new_files=files.replace('_','')