0

I am new to scripting and trying to write a python script to remove a few files.. Here is the path Multiple scripts/script*

Main directory: Multiple scripts
sub directories: script1
                 script2
                 script3

In each script in subdirectories, I have file consists of mem. Since I don't know what they start with or their extension now I would like to write a script to search all the subdirectories and delete files that consists of mem.

I tried using the following code but did not work for me

import os
if Multiple scripts/scripts*
    os.remove(*/mem*)
else:
    print ("file does not exists")

And also please help me with how to write a script to delete files with multiple names (/mem, /name) at a time. Any help would be appreciated... Thank you

user7090
  • 83
  • 6
  • What is “if Multiple” (supposed to be)? – Davis Herring Jun 14 '20 at 17:21
  • @Davis Herring What I mean is how can we write a script to delete two or more files with different names at a time – user7090 Jun 14 '20 at 17:28
  • Unless you are *specifically* asking about how to solve a cross-version compatibility problem (in which case your question should obviously describe that problem) you should not mix the [tag:python-2.7] and [tag:python-3.x] tags. – tripleee Jun 14 '20 at 17:29
  • 1
    See [Delete multiple files matching a pattern](https://stackoverflow.com/questions/1548704/delete-multiple-files-matching-a-pattern) & [How to delete a file or folder?](https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder) – Trenton McKinney Jun 14 '20 at 17:49

1 Answers1

0

If I'm understanding your question correctly, I think you'll want the glob module. Something like

import os
import glob
for fname in glob.iglob("./*/mem*"):
    print("Removing "+fname)
    os.remove(fname)

Before you run that loop, though, I'd say run it first without the last line, to see what it would do, and make sure that that's what you want.

ReGuess
  • 1
  • 1
  • 2
  • how about the path? I mean where it should go and delete – user7090 Jun 14 '20 at 17:44
  • @user7090 If you're running the script from some other directory, you'd replace the "." with the path to the base directory. The "." here simply indicates a "relative path", telling it to search the current directory. – ReGuess Jun 14 '20 at 17:52
  • It didnot print anything – user7090 Jun 14 '20 at 18:06
  • @user7090 It's not clear what the problem is. How about you read [this](https://en.wikipedia.org/wiki/Path_%28computing%29#Absolute_and_relative_paths) and see if it clears anything up. – ReGuess Jun 14 '20 at 18:20