nunos
nunos

Reputation: 21409

How to create a file one directory up?

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.

Upvotes: 18

Views: 29616

Answers (3)

Ned Batchelder
Ned Batchelder

Reputation: 375942

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")

Upvotes: 20

Johannes Rudolph
Johannes Rudolph

Reputation: 35761

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.

Upvotes: 2

u0b34a0f6ae
u0b34a0f6ae

Reputation: 49833

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

import os
fobj = open(os.path.join(os.pardir, "filename"), "w")

Upvotes: 35

Related Questions