How do I remove/unlink wildcarded files

Ervin Hegedüs airween at gmail.com
Fri Jan 2 12:00:00 CET 2015


Hi,

On Fri, Jan 02, 2015 at 09:21:53PM +1100, Cameron Simpson wrote:
> On 02Jan2015 10:00, Ervin Hegedüs <airween at gmail.com> wrote:
> >On Thu, Jan 01, 2015 at 05:13:31PM -0600, Anthony Papillion wrote:
> >>I have a function I'm writing to delete wildcarded files in a directory.
> >>I tried this:
> >>
> >>def unlinkFiles():
> >>    os.remove("/home/anthony/backup/unix*")
> >>
> >>This doesn't seem to work because it's a wildcard filename. What is the
> >>proper way to delete files using wildcards?
> >
> >Now I didn't checked, but once I've used some like this:
> >
> >def unlinkFiles():
> >   dirname = "/path/to/dir"
> >   for f in os.listdir(dirname):
> >       if re.match("^unix*$", f):
> >           os.remove(os.path.join(dirname, f))
> 
> That is a very expensive way to check the filename in this
> particular case.  Consider:
> 
>  if f.startswith('unix'):
> 
> instead of using a regular expression.

well, that's true - but that works only the example above.

> But generally the OP will probably want to use the glob module to
> expand the shell pattern as suggested by others.

I didn't know the glob module before, but yes, that's better
solution for this - but as I see, that also uses os.listdir()
(and fnmatch modue).


Anyway, thanks for the tip.


a.

-- 
I � UTF-8



More information about the Python-list mailing list