How to create a file in one directory?

How to create a file in python in one directory up without using the full path?

I need a way that worked for both windows and linux.

Thank.

+11
python io
Oct 22 '09 at 2:44
source share
3 answers

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

 import os fobj = open(os.path.join(os.pardir, "filename"), "w") 
+23
Oct 22 '09 at 14:45
source share

People don't seem to understand this, but Python is happy to accept the slash even on Windows. This works great on all platforms:

 fobj = open("../filename", "w") 
+7
Oct 22 '09 at 15:05
source share

Depends on whether you work in a unix or windows environment.

In the windows:

 ..\foo.txt 

On unix as OS:

 ../foo.txt 

you need to make sure that os sets the current path correctly when starting the application. Take the appropriate path and just create a file there.

0
Oct 22 '09 at 14:46
source share



All Articles