tags:

views:

39

answers:

2

Hello. I am running a script that walks a directory structure and generates new files in each folder in the directory. I want to delete some of the files right after creation. This is my idea, but it is quite wrong I imagine:

directory = os.path.dirname(obj)
m = MeshExporterApplication(directory)
os.remove(os.path.join(directory,"*.mesh.xml"))

How to you put wildcards in a path? I guess not like /home/me/*.txt, but that is what I am trying.

Thanks, Gareth

+4  A: 

You can use the glob module:

import glob
glob.glob("*.mesh.xml")

to get a list of matching files. Then you delete them, one by one.

directory = os.path.dirname(obj)
m = MeshExporterApplication(directory)

# you can use absolute pathes in the glob
# to ensure, that you're purging the files in 
# the right directory, e.g. "/tmp/*.mesh.xml"
for f in glob.glob("*.mesh.xml"):
    os.remove(f)
The MYYN
He'll also need `os.path.join`.
Matthew Flaschen
Or absolute pathes in the glob.
The MYYN
A: 

do a for loop with the list of files as the thing you are looping over.

directory = os.path.dirname(obj)
m = MeshExporterApplication(directory)
for filename in os.listdir(dir):
    if not(re.match(".*\.mesh\".xml ,filename) is None):
        os.remove(directory + "/" + file)     
Roman A. Taycher
`glob.glob` aside, there is the `fnmatch` module, which means “filename matching” and is more appropriate than `re` for… well, matching filenames.
ΤΖΩΤΖΙΟΥ