0

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)
Joshua Morse
  • 1
  • 1
  • 1
  • That's because `listdir` will also list all the subdirectories under the path you provide, this might be helpful: https://stackoverflow.com/questions/22207936/python-how-to-find-files-and-skip-directories-in-os-listdir – fixatd Jan 27 '20 at 17:30
  • `os.listdir` always returns a list a file *names*, not full paths. So you need to do `dirpath = '/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'` then `for filename in os.listdir(dirpath): x = os.path.join(dirpath, filename)`. – ekhumoro Jan 27 '20 at 18:26
  • @ekhumoro this worked, thanks! – Joshua Morse Jan 27 '20 at 19:45

0 Answers0