tags:

views:

145

answers:

3

How can I create a file in python one directory up, without using the full path?

I would like a way that worked both for windows and linux.

Thanks.

+8  A: 

Use os.pardir (which is probably always "..")

import os
fobj = open(os.path.join(os.pardir, "filename"), "w")
kaizer.se
will that work for both Windows and Linux?
nunos
by using os.pardir it will take the relevant parent directory syntax for the OS your application is currently running on. So yes, it will work on both Windows and Linux.
tomlog
Thanks. That was quick!
nunos
`os.path.join` uses the right kind of directory separators for the OS (`:` for Mac OS 9 etc..). `os.pardir` the correct parent directory name, but does anyone know any OS not using `".."`?
kaizer.se
OpenVMS uses very different directory syntax; but os.pathsep still returns ".." and you can use Unix-style paths within python with no problem.
Dave Costa
A: 

Depends whether you are working in a unix or windows environment.

On windows:

..\foo.txt

On unix like OS:

../foo.txt

you need to make sure the os sets the current path correctly when your application launches. Take the appropriate path and simply create a file there.

Johannes Rudolph
use os.path.join or os.sep
Anurag Uniyal
Python will understand forward slash on Windows, too.
mobrule
I'm no python guy :-)
Johannes Rudolph
+2  A: 

People don't seem to realize this, but Python is happy to accept forward slash even on Windows. This works fine on all platforms:

fobj = open("../filename", "w")
Ned Batchelder
Is this an official feature? I don't remember seeing it in the documentation, and os.path.join always made me think that programmers should not rely on '/' being the path separator…
EOL