使用Shutil Python模块移动文件时出现FileNotFound错误

3
我编写了以下代码来识别和组织gif和图像文件。 cdir是程序应该组织的目录。当它被执行时,它应该在同一目录下创建文件夹“Gifs”和“Images”。
import shutil, os

gifext = ['.gif', 'gifv']
picext = ['.png', '.jpg']

for file in files:
   if file.endswith(tuple(gifext)):
       if not os.path.exists(cdir+'\Gifs'):
           os.makedirs(cdir + '\Gifs')
       shutil.move(cdir + file, cdir + '\Gifs')

   elif file.endswith(tuple(picext)):
       if not os.path.exists(cdir+'\Images'):
           os.makedirs(cdir + '\Images')
       shutil.move(cdir + file, cdir + '\Images')

该目录包含文件:FIRST.gif,SECOND.gif和THIRD.jpg。
但是我遇到了以下错误:
  File "test.py", line 16
    shutil.move(cdir + file, cdir + '\Gifs')
  File "C:\Users\stavr\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 552, in move
    copy_function(src, real_dst)
  File "C:\Users\stavr\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 251, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Users\stavr\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 114, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\stavr\\Desktop\\testFIRST.gif'

1
这个问题不应该被踩。是的,对于经验丰富的Python程序员来说,这个问题有点琐碎。但是这个问题绝对是典范:清晰的问题陈述,期望结果/实际结果,完整、自包含和可执行的代码,完整的回溯信息。 - Lukas Graf
感谢您的回复! - Smich
3个回答

3

files只包含目录中文件的名称。cdir末尾没有反斜杠,因此当您将cdirfiles中的元素连接起来时,可能会得到一个无效的路径:

"C:\stuff\my\path" + "file_name.png"
# equals
"C:\stuff\my\pathfile_name.png"

后者显然不是您想要的,因此您应该以某种方式向添加反斜杠,可能像这样:
if not cdir.endswith("\\"):
    cdir += "\\"

1
cdir.endswith(os.sep): 更好,或建议使用 os.path.join 和原始字符串。 - Jean-François Fabre

1

您的文件路径不正确。缺少路径分隔符。

shutil.move(os.path.join(cdir, file), os.path.join(cdir, 'Gifs'))

1
不要手动拼接路径,应该使用os.path.join。这将首先避免此错误,并且还会生成可移植的代码。 - Lukas Graf

0

错误报告指出,在您的目录“test”和文件“FIRST.gif”之间的路径中缺少“\”:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\stavr\\Desktop\\testFIRST.gif'

您可以通过在路径中添加“\”来解决此问题,例如:

Enter path to the directory: C:\Users\stavr\Desktop\test\

或者

替换:

shutil.move(cdir + file, cdir + '\Gifs')

作者:

shutil.move(os.getcwd() + '/' + file, cdir + '\Gifs')

顺便说一下: 我认为在“gifv”之前缺少一个“.”
gifext = ['.gif', 'gifv']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接