我正在尝试制作一个简单的程序,将所有具有用户指定扩展名的文件复制到另一个文件夹中。代码如下,报错如下:
#! 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] No such file or directory: 'alice.txt'
Alice.txt 是它应该复制的文件夹中的.txt 文件之一,所以它明明找到了?这是怎么回事?
它没有找到它,因为如果你没有指定文件夹,Python 只会在放置脚本的文件夹中查找文件,修复应该只是:
shutil.copy(os.path.join(folder_name, filename))