how to create file with spaces

Fredrik Lundh fredrik at pythonware.com
Thu Apr 6 06:26:54 EDT 2006


s99999999s2003 at yahoo.com wrote:

> 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

os.path.join joins path elements, so that's entirely expected.

try

    filename = dirpath + "-dummy"
    if not os.path.isfile(filename):
        open(filename, "w").close()

instead.  or if you want to "touch" the file even if it already exists,
just do

    open(dirpath + "-dummy", "w").close()

(to only touch a file if it exists, you can use os.utime(filename, None)
instead)

</F>






More information about the Python-list mailing list