我想制作一个 Python 脚本,以根据扩展名快速将桌面上的文件组织到文件夹中。基本上,我如何使用循环获取文件、对其执行某些操作、转到下一个文件等等?
最佳答案
您需要的一切可能都包含在 os
中图书馆,更具体地说在os.path
一点点和shutil
一个。
要浏览目录树,您可以使用 os.walk
并移动文件你可以使用 shutil.move
.
编辑:我编写的一个小脚本让你继续:
import os
import shutil as sh
from collections import defaultdict
DESKTOP = '/home/mac/Desktop'
#This dictionary will contain: <extension>: <list_of_files> mappings
register = defaultdict(list)
#Populate the register
for dir_, dirs, fnames in os.walk('/home/mac/Desktop'):
for fname in fnames:
register[fname.rsplit('.', 1)[1]].append(os.path.join(dir_, fname))
#Iterate over the register, creating the directory and moving the files
#with that extension in it.
for dirname, files in register.iteritems():
dirname = os.path.join(DESKTOP, dirname)
if not os.path.exists(dirname):
os.makedirs(dirname)
for file_ in files:
sh.move(file_, dirname)
关于python - 在目录和子目录中查找扩展名的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10273132/