简体   繁体   English

如何在特定路径创建文件?

[英]How do I create a file at a specific path?

In python I´m creating a file doing:在 python 中,我正在创建一个文件:

f = open("test.py", "a")

where is the file created?文件在哪里创建? How can I create a file on a specific path?如何在特定路径上创建文件?

f = open("C:\Test.py", "a")

returns error.返回错误。

The file path "c:\\Test\\blah" will have a tab character for the `\\T'. 文件路径"c:\\Test\\blah"将包含“\\ T”的制表符。 You need to use either: 你需要使用:

"C:\\Test"

or 要么

r"C:\Test"

I recommend using the os module to avoid trouble in cross-platform. 我建议使用os模块以避免跨平台的麻烦。 ( windows,linux,mac ) windows,linux,mac

Cause if the directory doesn't exists, it will return an exception. 如果目录不存在,则会返回异常。

import os

filepath = os.path.join('c:/your/full/path', 'filename')
if not os.path.exists('c:/your/full/path'):
    os.makedirs('c:/your/full/path')
f = open(filepath, "a")

If this will be a function for a system or something, you can improve it by adding try/except for error control. 如果这是系统或其他东西的功能,您可以通过添加try / except进行错误控制来改进它。

where is the file created? 文件在哪里创建?

In the application's current working directory. 在应用程序的当前工作目录中。 You can use os.getcwd to check it, and os.chdir to change it. 您可以使用os.getcwd来检查它,并使用os.chdir来更改它。

Opening file in the root directory probably fails due to lack of privileges. 由于缺少权限,根目录中的打开文件可能会失败。

It will be created once you close the file (with or without writing). 关闭文件后(有或没有写入)将创建它。 Use os.path.join() to create your path eg 使用os.path.join()创建路径,例如

filepath = os.path.join("c:\\","test.py")

The file is created wherever the root of the python interpreter was started. 无论python解释器的根目录何处启动,都会创建该文件。

Eg, you start python in /home/user/program , then the file "test.py" would be located at /home/user/program/test.py 例如,你在/home/user/program启动python,然后文件“test.py”将位于/home/user/program/test.py

f = open("test.py", "a") Will be created in whatever directory the python file is run from. f = open(“test.py”,“a”)将在运行python文件的任何目录中创建。

I'm not sure about the other error...I don't work in windows. 我不确定其他错误...我不在Windows中工作。

The besty practice is to use '/' and a so called 'raw string' to define file path in Python. 最好的做法是使用'/'和所谓的'原始字符串'来定义Python中的文件路径。

path = r"C:/Test.py"

However, a normal program may not have the permission to write in the C: drive root directory. 但是,正常程序可能没有在C:驱动器根目录中写入的权限。 You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so. 您可能需要允许您的程序这样做,或者选择更合理的东西,因为您可能不需要这样做。

Use os module使用操作系统模块

filename = "random.txt"

x = os.path.join("path", "filename")

with open(x, "w") as file:
    file.write("Your Text")
    file.close

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM