Deleting files from folder
Question:
I have files in folder with names 1.jpg, 2.jpg, 3.jpg … etc.
And I have list of names 2.jpg, 3.jpg, 4.jpg
How can I delete files in folder according to names from this list?
import os
import glob
fileList = glob.glob(‘/home/varung/Documents/python/logs/**/*.txt’,
recursive=True)
for filePath in fileList:
try:
os.remove(filePath)
except OSError:
print("Error while deleting file")
I don’t understand why quotes don’t work.
I found this code but it only works for patterns. I can’t understand how to put names from list inside. I need to delete files in folder if their names match names from list.
Answers:
this code does what you’ve described:
import os
removals = ['a.txt', 'b.jpg']
for object in os.listdir('.'):
if os.path.isfile(object) and object in removals:
os.remove(object)
I have files in folder with names 1.jpg, 2.jpg, 3.jpg … etc.
And I have list of names 2.jpg, 3.jpg, 4.jpg
How can I delete files in folder according to names from this list?
import os
import glob
fileList = glob.glob(‘/home/varung/Documents/python/logs/**/*.txt’,
recursive=True)for filePath in fileList:
try:
os.remove(filePath)
except OSError:
print("Error while deleting file")
I don’t understand why quotes don’t work.
I found this code but it only works for patterns. I can’t understand how to put names from list inside. I need to delete files in folder if their names match names from list.
this code does what you’ve described:
import os
removals = ['a.txt', 'b.jpg']
for object in os.listdir('.'):
if os.path.isfile(object) and object in removals:
os.remove(object)