初学者在这里。我希望能够遍历文件夹及其子目录和文件,并将所有唯一的文件扩展名移动到该文件类型的专用文件夹中。例如 .jpg -> 进入 jpg 文件夹。(这一切都在 Python 的 IDLE 中)
我有这个代码:
os.chdir('c:\\users\\dchrie504\\Downloads_2')
# walk through all files and folders to get unique filetypes.
l_Files = os.walk('c:\\users\\dchrie504\\Downloads_2')
fileTypes = []
for walk in l_Files:
for file in walk[-1]:
fileTypes.append(file.split('.')[-1])
# make all items lowercase to create distinct values
fileTypes = [x.lower() for x in fileTypes]
# get rid of duplicate filetypes by creating set then back to list.
fileTypes = set(fileTypes)
fileTypes = list(fileTypes)
# create a folder for each unique filetype.
for ft in fileTypes:
os.mkdir(os.getcwd() + '\\' + ft)
fileWalk = os.walk('c:\\users\\dchrie504\\Downloads_2')
#Trying to move files to their respective fileType folder.
for fileType in fileTypes:
for folder, sub, files in os.walk('c:\\users\\dchrie504\\Downloads_2'):
for file in files:
if file.endswith('.' + fileType):
shutil.move(file, (os.getcwd() + '\\' + fileType))
问题是执行此部分时出现以下错误:
for file in files:
if file.endswith('.' + fileType):
shutil.move(file, (os.getcwd() + '\\' + fileType))
错误消息:回溯(最近一次调用):文件“”,第 5 行,在 shutil.move(file, (os.getcwd() + '\' + fileType)) 文件“C:\Users\dchrie504\AppData\ Local\Programs\Python\Python37-32\lib\shutil.py”,第 555 行,在移动中引发错误(“目标路径 '%s' 已存在”% real_dst)shutil.Error: 目标路径 'c:\users\ dchrie504\Downloads_2\txt\New Text Document.txt' 已经存在