我在尝试使用python复制文件时收到此errno 2

问题描述

我正在尝试从目录及其所有基础文件夹移动许多文件,但是当我运行代码时。该脚本找不到第一个.pdf文件。我觉得很奇怪,因为文件确实存在

import shutil
import os
#Change the working directory to where files are located
os.chdir("C:\\Users\\vhole\\iCloudDrive\\BA_Historie\\")

#Get current working directory
directory = os.getcwd()
print(f"Current working directory is {directory}")
#Walking through a folder tree
for folders,subfoldes,filenames in os.walk('C:\\Users\\vhole\\iCloudDrive\\BA_Historie\\'):
    for filename in filenames:
        if filename.endswith('.jpg') or filename.endswith('.pdf'):
            shutil.copy(filename,'C:\\Users\\vhole\\iCloudDrive\\BA_Historie\\Samlede_tekster\\',follow_symlinks = True)

这是我得到的追溯和错误

Traceback (most recent call last):
  File "project13.py",line 18,in <module>
    shutil.copy(filename,follow_symlinks = True)
  File "C:\Users\vhole\AppData\Local\Programs\Python\python37\lib\shutil.py",line 248,in copy
    copyfile(src,dst,follow_symlinks=follow_symlinks)
  File "C:\Users\vhole\AppData\Local\Programs\Python\python37\lib\shutil.py",line 120,in copyfile
    with open(src,'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'Det_moderne_norden_program.pdf'

解决方法

Python尝试从工作目录(即您输入的目录)中复制文件。因此,如果您的pdf文件不直接位于其中,而是位于其子目录之一中,则复制将失败。因此,一种解决方案是将子目录路径放在filename之前。所以代替:

            shutil.copy(filename,'C:\\Users\\vhole\\iCloudDrive\\BA_Historie\\Samlede_tekster\\',follow_symlinks = True)

尝试:

            shutil.copy(os.path.join(folders,filename),follow_symlinks = True)