我正在尝试根据文件扩展名对大量文件进行排序。很多文件都是.doc,.docx,.xls等。
这就是我脑子里的想法,但如果有更简单的方法可以做,请告诉我!我有多个具有相同扩展名的文件,因此我不希望它每次都为该扩展名创建一个新文件夹并覆盖以前的文件。我还有一个更大的列表,但是对于这个例子,我不相信所有这些都是必需的。操作系统是MacOS。
import os, shutil
extList = ['.doc', '.docx', '.xls']
for ext in extList:
os.mkdir(path + '/' + ext +'_folder')
for file in os.listdir(filepath):
if file.endswith(ext): #missing an indent
print(file)
shutil.copyfile(file + '/' + ext +'_folder' + file)
另外,如果我遇到列表中没有的文件,我希望它进入名为'noextlist'的文件夹。
答案 0 :(得分:1)
这是我能够快速创建的
import os, re, shutil
DocFolder = r'...'#Your doc folder path
DocxFolder = r'...'#Your docx folder path
XlsFolder = r'...'#Your xls folder path
MiscFolder = r'...'#Your misc folder path
for root, dirs, files in os.walk(r'...'): #Your folder path you want to sort
for file in files:
if file.endswith(".doc"):
sourceFolder = os.path.join(root,file)
print sourceFolder
shutil.copy2(sourceFolder,DocFolder)
elif file.endswith(".docx"):
sourceFolder = os.path.join(root,file)
print sourceFolder
shutil.copy2(sourceFolder,DocxFolder)
elif file.endswith(".xls"):
sourceFolder = os.path.join(root,file)
print sourceFolder
shutil.copy2(sourceFolder,XlsFolder)
else:
sourceFolder = os.path.join(root,file)
print sourceFolder
shutil.copy2(sourceFolder,MiscFolder)
编辑:这里的主要功能是for root,dirs,files in os.walk
这允许程序横穿提供的路径搜索所有文件,包括子文件夹中的文件,并相应地对其进行排序。
答案 1 :(得分:1)
{{1}}
答案 2 :(得分:0)
如果我理解正确,你喜欢你的解决方案但是你需要一种方法来重命名具有重复名称的文件,这样额外的东西就不会消失。您可以检查目标文件是否已存在,并通过将_1
,_2
等添加到文件名来构建变体名称,直到找到未使用的内容。
newpathname = path + '/' + ext +'_folder' + "/" + file
n = 0
while os.path.exists(newpathname):
n += 1
base, ext = os.path.splitext(newpathname)
newpathname = "%s_%d%s" % (base, n, ext)
shutil.copyfile(filepath+"/"+file, newpathname)
但是你的代码还有其他一些故障,所以这里是一个重写的扫描仪。它使用os.walk()
下降到几个级别的子目录(您不会说是否需要),并且它在一次传递中收集所有扩展的文件。它像以前一样构造变体名称。
import os, shutil
extList = ['.doc', '.docx', '.xls']
from os.path import join as joinpath
# Make sure the destination directories exist
for ext in extList:
extdir = joinpath(path, ext[1:]+"_folder")
if not os.path.exists(extdir):
os.mkdir(extdir)
for dirname, _dirs, files in os.walk(filepath):
for file in files:
base, ext = os.path.splitext(file)
if ext not in extList:
continue
destpath = joinpath(path, ext[1:]+"_folder")
n = 0
newpathname = joinpath(destpath, file)
# If the new name is in use, find an unused variant
while os.path.exists(newpathname):
n += 1
newfile = "%s_%d%s" % (base, n, ext)
newpathname = joinpath(path, newfile)
sh.copy(joinpath(dirname, file), newpathname) # or other copy method