how to touch a file

Diez B. Roggisch deets at nospam.web.de
Thu Apr 6 06:29:45 EDT 2006


s99999999s2003 at yahoo.com wrote:

> hi
> 
> i have a dir that contains directories with names and spaces in between
> example
> 
> rootdir
>    | ----> ABC DEF A
>    | ---> BDD SD N
> 
> I wanted to touch a file with the same name as the directories inside
> each directory
> 
> rootdir
>    | ----> ABC DEF A
>                   |-------> ABC DEF A-dummy
>    | ---> BDD SD N
>                   |-------> BDD SD N-dummy
> 
> heres the code :
> for d in os.walk(rootdir):
>         (dirpath, dirnames, filenames) = d
>         for dir in [dirpath]:
>                 if not os.path.exists( os.path.join(dir,"-dummy") ):
>                         f = open( os.path.join(dir,"-dummy") ,
> "w").write("")
> 
> but i got only "-dummy" as the filename in each directory
> 
> How can i deal with spaces in this case? or is there some wrong things
> i do in the code?

os.path.join joins paths with the proper OS-dependend separator. So 

os.path.join("a", "b", "c")

becomes

a/b/c

under unix.  Naturally, joining dir and "-dummy" produces "<dir>/-dummy" -
which is what you see. 

Instead, do something like this:

for d in os.walk(rootdir):
         (dirpath, dirnames, filenames) = d
         for dir in [dirpath]:
                 fname = os.path.basename(dir) + "-dummy"
                 if not os.path.exists( os.path.join(dir,fname) ):
                         f = open( os.path.join(dir,fname) ,
 "w").write("")


Diez




More information about the Python-list mailing list