如何使用shutil.copy修复Python 3中的“ FileNotFoundError:[Errno 2]”

时间:2019-02-05 14:57:19

标签: python python-3.x

我正在使用“用Python自动化乏味的东西”中的练习编写程序。我相信我有一个可以正常工作的原型,但是我正在使用shutil.copy收到文件未找到错误。该程序应该使用用户提供的扩展名,源目录和目标目录来选择性地复制文件。

我在末尾添加了一些打印测试,如果我将shutil.copy注释掉,它们将打印正确的文件名和到目标目录的正确绝对路径。

如果我取消注释shutil.copy,则会出现此错误:

Traceback (most recent call last):
  File "selectiveCopy.py", line 30, in <module>
    shutil.copy(filename, copyDirAbs)
  File "/usr/lib/python3.4/shutil.py", line 229, in copy
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "/usr/lib/python3.4/shutil.py", line 108, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'testfile2.txt'

似乎shutil.copy对文件的路径感到困惑,但是它提供的是“正确的”文件名?这些文件不是符号链接,但确实存在。

#!/usr/bin/python3
# Selective Copy - walks a directory tree looking for a specified
# file type and copying it to a specified directory

# All my directory paths seem correct, so it's something
# with the shutil.copy command and the path that's getting
# borked?

import shutil, os

# Ask what extension to look for
extension = input('What file extension am I copying?')

# Ask what folder to copy files to, and TODO: create it if it doens't exist
copyDir = input('What directory am I copying to?')
copyDirAbs = os.path.abspath(copyDir)

# Ask what directory to search
searchDir = input('What directory do you want me to look in?')
searchDirAbs = os.path.abspath(searchDir)

# Recursively walk the Search Directory, copying matching files
# to the Copy Directory
for foldername, subfolders, filenames in os.walk(searchDirAbs):
    print('Searching files in %s...' % (foldername))
    for filename in filenames:
        if filename.endswith('.%s' % extension):
            print('Copying ' + filename)
            print('Copying to ' + copyDirAbs)
            shutil.copy(filename, copyDirAbs)


print('Done.')

2 个答案:

答案 0 :(得分:1)

这里的一个问题是您没有指定文件的路径。从父目录执行命令时,脚本无法知道testfile2.txt在输入目录的子目录中。要解决此问题,请使用:

shutil.copy(os.path.join(foldername, filename), copyDirAbs)

答案 1 :(得分:0)

感谢您的建议。我通过以下方式连接目录路径和文件名来修复它:

# Recursively walk the Search Directory, copying matching files
# to the Copy Directory
for foldername, subfolders, filenames in os.walk(searchDirAbs):
    print('Searching files in %s...' % (foldername))
    for filename in filenames:
        if filename.endswith('.%s' % extension):
            print('Copying ' + filename)
            print('Copying to ' + copyDirAbs)
            totalCopyPath = os.path.join(searchDirAbs, filename)
            shutil.copy(totalCopyPath, copyDirAbs)

print('Done.')

它现在似乎可以正常工作。