"Moving a directory into itself" Python 中的错误



我有一个应用程序,它在接收到包含文件的文件夹的路径时对文件进行排序。然而,有一行代码,我应该把一个目录移动到它自己,但我不知道这是怎么发生的,因为我对其他部分做了同样的事情,他们没有导致错误。

这是包含错误的部分。

导致错误的部分是最后一个块,我试图将其他文件移动到" other "文件夹。

我尝试在shutil.move()中更改目的地,但错误仍然存在。

os.chdir(path)
new_folder = "Sorted Files"
os.makedirs(new_folder)
path_2 = path+"/"+new_folder
os.chdir(path_2)
new_folder_doc = "Documents"
new_folder_texts = "Texts"
new_folder_images = "Images"
new_folder_other = "Other"
os.makedirs(new_folder_doc)
os.makedirs(new_folder_texts)
os.makedirs(new_folder_images)
os.makedirs(new_folder_other)

for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isfile(file_path):
file_name = os.path.basename(file_path)
#  Sorting files
if file_path.endswith('.png') or file_path.endswith('.gif') or file_path.endswith('.bmp') or
file_path.endswith('.jpg') or file_path.endswith('.jpeg') is True:
shutil.move(file_path, new_folder_images)
continue
if file_path.endswith('.txt') or file_path.endswith('.ini') or file_path.endswith('.log') is True:
shutil.move(file_path, new_folder_texts)
continue
if file_path.endswith('.pdf') or file_path.endswith('.docx') or file_path.endswith('.doc') or
file_path.endswith('.xls') or file_path.endswith('.xlsx') or file_path.endswith('.csv') is True:
shutil.move(file_path, new_folder_doc)
continue
if file_path.endswith('.docx') or file_path.endswith('.txt') or file_path.endswith('.bmp') or 
file_path.endswith('.png') or file_path.endswith('.ini') or file_path.endswith('.log') 
or file_path.endswith('.gif') or file_path.endswith('.doc') or file_path.endswith('.dir') 
or file_path.endswith('.xls') or file_path.endswith('.xlsx') or file_path.endswith('.csv') 
or file_path.endswith('.jpg') or file_path.endswith('.jpeg') or file_path.endswith('.pdf') is not True:
shutil.move(file_path, new_folder_other)
continue

os.listdir列出文件和目录。在最后一个块中,尝试移动每个不以".pdf"结尾的文件/目录。这对于"其他"是正确的;目录。

要在代码中修复它,您可以只对文件而不是目录执行排序。您可以通过添加以下代码轻松跳过for循环中的目录,以检查"file_path"-variable是否实际引用了文件:

if not os.path.isfile(file_path):
continue

另外,您可能需要再次检查您的" endswith"条件。is Trueis not True只适用于最后一个条件,而不是全部(我认为这是你正在寻找的)。

最新更新