python fileNotfound误差从OS.WALK循环循环
我正在尝试制作一个真正的基本脚本来对屏幕快文件夹进行排序:我想将目录中存储的所有文件复制到一年和月份的子目录中,并在此时删除原始文件。我现在拥有的代码完全为此目的起作用,但是当运行仍然会出现此文件错误时,因为它试图在已经复制和删除的一个文件上作用:
filenotfounderror:[errno 2]没有这样的文件或目录:'c:\\用户\\ me \\ desktop \\练习folder \\ ffxiv_06122021_193007_114.png'
我已经验证了该文件已经被复制/删除了。该脚本是功能性的,但我想添加更多代码来创建输出文件记录已完成的操作,并且此错误使我有点障碍。我觉得我一定缺少关于循环非常明显的东西。这是我编写的代码:
import os
import shutil
filedir = "C:\\Users\\Me\\Desktop\\PracticeFolder"
month_dict = {
"01" : "01 January",
"02" : "02 February",
"03" : "03 March",
"04" : "04 April",
"05" : "05 May",
"06" : "06 June",
"07" : "07 July",
"08" : "08 August",
"09" : "09 September",
"10" : "10 October",
"11" : "11 November",
"12" : "12 December"
}
for root, dirs, files in os.walk(filedir):
for filename in files:
#Storing the month and year from filename as a slice
year_slice = filename[10:14]
month_slice = filename[8:10]
month_name = month_dict.get(month_slice)
#\\ used to avoid Windows unicode errors
old_path = filedir + "\\" + filename
new_path = filedir + "\\" + year_slice + "\\" + month_name
shutil.copy(old_path, new_path)
os.remove(old_path)
I'm trying to make a really basic script to sort a screenshot folder: I want to copy all of the files stored in the directory into subdirectories by year and month, and remove the original files as I do so. The code I have right now is entirely functional for this purpose, but when run still gives this FileNotFound error because it's trying to act on one of the files that's already been copied and removed:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Me\\Desktop\\PracticeFolder\\ffxiv_06122021_193007_114.png'
I've verified that this file has been copied/removed already. The script is functional but I'd like to add some more code to create an output file recording what's been done and this error is roadblocking me a bit. I feel like I must be missing something very obvious regarding the loop. Here's the code I've written:
import os
import shutil
filedir = "C:\\Users\\Me\\Desktop\\PracticeFolder"
month_dict = {
"01" : "01 January",
"02" : "02 February",
"03" : "03 March",
"04" : "04 April",
"05" : "05 May",
"06" : "06 June",
"07" : "07 July",
"08" : "08 August",
"09" : "09 September",
"10" : "10 October",
"11" : "11 November",
"12" : "12 December"
}
for root, dirs, files in os.walk(filedir):
for filename in files:
#Storing the month and year from filename as a slice
year_slice = filename[10:14]
month_slice = filename[8:10]
month_name = month_dict.get(month_slice)
#\\ used to avoid Windows unicode errors
old_path = filedir + "\\" + filename
new_path = filedir + "\\" + year_slice + "\\" + month_name
shutil.copy(old_path, new_path)
os.remove(old_path)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题中显示的代码无法正确构建路径名。这是一种改进的方法:
The code shown in the question doesn't build pathnames correctly. Here's an improved approach: