[Newbie Question] Matching directory content with variable

Chris Liechti cliechti at gmx.net
Sat May 11 11:48:36 EDT 2002


Marcus Klein <marcus1 at marcus1.de> wrote in 
news:h1ajba.ni5.ln at news.marcus1.de:
> Hi out there,
> 
> I am trying to match a directory content with a variable to avoid 
> overwriting an existing file and it does not work.
> 
> Maybe someone knows why ?
> 
> --8<--
> for f in TOGET:
>     print "getting remote file ", f
>     fname = PATHTOFILE + f

you should use os.path.join to make paths...

>     lfiles = os.listdir(PATHTOFILE)

listdir gives back a list of strings and you should call it
with a path to directory not with a file.

what you realy want is os.path.exists().

>     lfile = re.compile(f, re.M).match(lfiles, 1)

you don't need to use re.compile for that. there is re.match()
compile is useful when you store the compiled regex in a variable
when you use it often.

the exception is because you feed a list to it and not a string. use
the appropriate functions (i.e. exists) from os.path and you don't
have to worry.

>     if lfile:
>         print "Warning: File exists locally"
>         exit(5)
> -->8--
> 
> leads to
> 
> --8<--
> Traceback (most recent call last):
>   File "py/getftp.py", line 33, in ?
>     lfile = re.compile(f, re.M).match(lfiles, 1)
> TypeError: expected string or buffer
> -->8--

you should use the functions from os and os.path to manupulate paths and 
files. they save you from issues with '\' and '/', they work cross platform 
and save you from a lot of trouble anyway.

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list