python 如何创建一个文件一个目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1607751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a file one directory up?
提问by nunos
How can I create a file in python one directory up, without using the full path?
如何在不使用完整路径的情况下在 python 一个目录中创建一个文件?
I would like a way that worked both for windows and linux.
我想要一种既适用于 windows 又适用于 linux 的方法。
Thanks.
谢谢。
回答by u0b34a0f6ae
Use os.pardir
(which is probably always ".."
)
使用os.pardir
(这可能总是".."
)
import os
fobj = open(os.path.join(os.pardir, "filename"), "w")
回答by Ned Batchelder
People don't seem to realize this, but Python is happy to accept forward slash even on Windows. This works fine on all platforms:
人们似乎没有意识到这一点,但即使在 Windows 上,Python 也乐于接受正斜杠。这适用于所有平台:
fobj = open("../filename", "w")
回答by Johannes Rudolph
Depends whether you are working in a unix or windows environment.
取决于您是在 unix 还是 windows 环境中工作。
On windows:
在窗户上:
..\foo.txt
On unix like OS:
在像操作系统这样的 Unix 上:
../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.
您需要确保操作系统在您的应用程序启动时正确设置当前路径。选择合适的路径并在那里创建一个文件。