0

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 :)

3
  • 2
    Would you mind editing your post and showing us what you've attempted so far? Commented Jul 29, 2020 at 13:39
  • But... what exactly IS the condition? Commented Jul 29, 2020 at 13:58
  • @Tomerikoo: I have the folder has many files. I am checking one image after another and extracting the text. The place where I get the word "Achieved", I delete all the remaining files of higher numbers. So sometimes, the file numbers (in file names) may change. Hope am making sense. Commented Jul 29, 2020 at 15:24

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Thanks... But the folder has many files. I am checking one image after another. The place where I get the word "Achieved", I delete all the remaining files of higher numbers. So sometimes, the file numbers (in file names) may change. Hope am making sense. Thanks for your guidance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.