开发者

How to create a file one directory up?

开发者 https://www.devze.com 2022-12-08 23:52 出处:网络
How can I create a file in python one directory up, without using the full pa开发者_JS百科th? I would like a way that worked both for windows and linux.

How can I create a file in python one directory up, without using the full pa开发者_JS百科th?

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

Thanks.


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

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消