I am trying to write a program that will delete files inside a specific folder.
When I run the following code, I get the error:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/Programming/python/deletefiles/1.txt
My code:
import os, sys
for filename in os.listdir('/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'):
print(filename)
x = os.path.realpath(filename) #not required but included so program would give more meaningful error
os.unlink(x)
when line 5 is commented out the program runs fine and lists all the files contained in the folder.
I do not understand why the error is cutting off the last folder (f2d
) in the directory path. Additionally if I miss type the last folder in the path to something like f2
it produces the following error: FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/programming/python/deletefiles/f2/
.
Why is the last folder included in the path only when it is mispelled? How would I go about fixing this so the correct path is passed?
Solution
Provided by @ekhumoro
os.listdir()
does not return the path, just the files names in the specified folder.
Corrected Code
import os
dirpath = '/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'
for filename in os.listdir(dirpath):
x = os.path.join(dirpath, filename)
os.unlink(x)