'How to loop through directory and delete files matching array of filenames in Python?
I would like to delete files that begin with the array values and end with "_1.txt", from this given directory. I have this so far, which deletes the files successfully, but it throws an error every time, "FileNotFoundError: [Errno 2] No such file or directory: 'tom_1.txt'". I think the loop is not ending somehow, but I cannot figure out how to fix it.
import os
directory = '/home/ec2-user/SageMaker/'
names = np.array(['tom','jen','bob'])
for filename in os.scandir(directory):
for name in names:
os.remove(f'{name}_1.txt')
Solution 1:[1]
os.scandir only returns the file names. You have to add the path:
os.remove( f'{directory}{name}_1.txt' )
However, unless every name exists, that might still fail. You might consider:
name = f'{directory}{name}_1.txt'
if os.path.isfile(name):
os.remove(name)
I didn't even notice you aren't using the result of os.scandir. You can remove that outer loop and this will still work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
