FileNotFoundError – the error says it cannot find the file it obviously did find

Question:

I am trying to make a simple program to copy all files with a user specified extension into another folder. The code is as follows and the error is below:

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

Here is the Error:

FileNotFoundError: [Errno 2] No such file or directory: ‘alice.txt’

Alice.txt is one of the .txt files in the folder it is supposed to copy, so it clearly found it? What is going on?

Asked By: Douglas Munsey

||

Answers:

It does not find it because if you do not specify a folder Python will only look for the file in the folder where the script is placed, the fix should simply be:

shutil.copy(os.path.join(folder_name, filename))
Answered By: Caridorc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.