所以我创建了一个基本的shutil.move()补丁来移动桌面上的文件。问题是,我指定了不存在的文件的目的地(在本例中为"文档"),现在我找不到我的文件。我的问题是,简单地说,鉴于此 Docs 命令不存在,我的文件去了哪里?
for f in files:
if f.endswith(('.docx', '.doc')):
shutil.move(os.path.join(root, f), "Docs")
else:
continue
实际上,根据我的评论(我刚刚测试了您的代码),您在这里实际所做的是一次接一个地获取一个或多个文件 (f) 并将它们移动到一个名为"Docs"的文件中。 我还没有测试过多个文件,但是如果你有很多文件,我会说,每个文件,你已经破坏(覆盖)了一个文件,最后在根目录中只得到一个名为"Docs"的单个文件。如果我理解您尝试做的事情是正确的,您希望将文件从当前位置移动到 root 内的另一个目录中。代码将是。
shutil.move(os.path.join(root, f), os.path.join(root, "Docs", f))
这也假定"文档"存在。 如果没有,那么您的代码将出错。执行以下操作之前的一行:
if not os.path.exists(os.path.join(root, "Docs")):
os.mkdir(os.path.join(root, "Docs"))
我使用的最终代码(假设这是你想要实现的):
import shutil
import os
root =('.') # for the sake of testing, I just used the base directory
files = os.listdir('.') # I also pulled filed from this directory for the sake of testing - I actually tested with a csv file, but the idea remains the same
for f in files:
if f.endswith((docx', '.doc')):
if not os.path.exists(os.path.join(root, "Docs")):
os.mkdir(os.path.join(root, "Docs"))
shutil.move(os.path.join(root, f), os.path.join(root, "Docs", f))
print(f)
else:
continue