FileNotFoundError - 错误表明它找不到它显然找到的文件
FileNotFoundError - the error says it cannot find the file it obviously did find
我正在尝试制作一个简单的程序来将具有用户指定扩展名的所有文件复制到另一个文件夹中。代码如下,报错如下:
#! 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 文件之一,所以它明明找到了?怎么回事?
找不到它是因为如果您不指定文件夹 Python 将只查找放置脚本的文件夹中的文件,修复应该只是:
shutil.copy(os.path.join(folder_name, filename))
我正在尝试制作一个简单的程序来将具有用户指定扩展名的所有文件复制到另一个文件夹中。代码如下,报错如下:
#! 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 文件之一,所以它明明找到了?怎么回事?
找不到它是因为如果您不指定文件夹 Python 将只查找放置脚本的文件夹中的文件,修复应该只是:
shutil.copy(os.path.join(folder_name, filename))