Reputation: 35
I am new to python and am trying the following:
I have 7 files in my directory.
MyFileName1.jpg
MyFileName2.jpg
MyFileName3.jpg
MineFileName1.jpg
MineFileName2.jpg
MineFileName3.jpg
MineFileName4.jpg
Based on a condition, I am trying to remove MyFileName2.jpg and MyFileName3.jpg. Please suggest.
Thanks in advance :)
Upvotes: 0
Views: 79
Reputation: 707
Simple:
import os
from pathlib import Path
folder = Path('path_to_your_dir')
names = ['MyFileName2.jpg', 'MyFileName3.jpg'] # Name of files to be deleted
for file in folder.iterdir():
if file.name in names:
os.remove(file)
Upvotes: 1
Reputation: 823
s.remove()
removes a file.
os.rmdir()
removes an empty directory.
shutil.rmtree()
deletes a directory and all its contents.
Path objects from the Python 3.4+ pathlib
module also expose these instance methods:
pathlib.Path.unlink()
removes a file or symbolic link.
pathlib.Path.rmdir()
removes an empty directory.
You can also use
import os
os.remove("file_path/<file_name>.txt")
Upvotes: 1