18

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.

nunos
  • 20,479
  • 50
  • 119
  • 154

3 Answers3

35

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

import os
fobj = open(os.path.join(os.pardir, "filename"), "w")
u0b34a0f6ae
  • 48,117
  • 14
  • 92
  • 101
  • 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. – Tom van Enckevort Oct 22 '09 at 14:49
  • `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 `".."`? – u0b34a0f6ae Oct 22 '09 at 14:59
  • 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 Oct 22 '09 at 15:31
19

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
  • 364,293
  • 75
  • 561
  • 662
  • 2
    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… – Eric O. Lebigot Oct 22 '09 at 17:50
2

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
  • 35,298
  • 14
  • 114
  • 172