gpt4 book ai didi

python - 如何使用shutil.copy修复Python 3中的 "FileNotFoundError: [Errno 2]"

转载 作者:行者123 更新时间:2023-12-01 01:14:05 28 4
gpt4 key购买 nike

我正在编写一个程序作为使用 Python 自动化无聊工作的练习。我相信我有一个工作原型(prototype),但我在使用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对文件的路径感到困惑,但它提供了“正确的”文件名?这些文件不是符号链接(symbolic link),它们确实存在。

#!/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.')

最佳答案

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

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

关于python - 如何使用shutil.copy修复Python 3中的 "FileNotFoundError: [Errno 2]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54537182/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com