FileNotFoundError - 错误说它无法找到它显然找到的文件

时间:2016-01-01 19:09:14

标签: python filenotfoundexception

我正在尝试创建一个简单的程序,将具有用户指定扩展名的所有文件复制到另一个文件夹中。代码如下,错误如下:

#! python3
# Copies all files from folder with user specified extension
import os, shutil

pmatch = []
num = 1
while True:
    print('Enter path ' + str(num) + ' or "end" to finish')
    pt = input()
    if pt.lower() == 'end':
        break
    pmatch.append(pt)
num = num + 1
pth = str()
for i in pmatch:
    pth = pth + str(i) + '/'

truepth = 'C:/' + pth
os.chdir(truepth)

print('Enter folder name to copy:')
folder_name = input()
print('Enter new folder name: ')
new_folder = input()
print('Enter extension to copy:')
ext = input()

orig_pth = truepth + folder_name 
new_pth = truepth + new_folder 

for folder_name, subfolders, filenames in os.walk(orig_pth):
    for filename in filenames:
        if filename.endswith(ext):
            shutil.copy(filename, new_pth)
            print(filename + ' copied')
print('Complete')

这是错误:

FileNotFoundError:[Errno 2]没有这样的文件或目录:'alice.txt'

Alice.txt是它应该复制的文件夹中的.txt文件之一,所以它清楚地找到了吗?发生了什么事?

1 个答案:

答案 0 :(得分:2)

它找不到它,因为如果你没有指定文件夹,Python将只查找脚本放置的文件夹中的文件,修复应该只是:

shutil.copy(os.path.join(folder_name, filename))