简体   繁体   中英

How do I create a file at a specific path?

In python I´m creating a file doing:

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'. You need to use either:

"C:\\Test"

or

r"C:\Test"

I recommend using the os module to avoid trouble in cross-platform. ( 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.

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.

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

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

The file is created wherever the root of the python interpreter was started.

Eg, you start python in /home/user/program , then the file "test.py" would be located at /home/user/program/test.py

f = open("test.py", "a") Will be created in whatever directory the python file is run from.

I'm not sure about the other error...I don't work in windows.

The besty practice is to use '/' and a so called 'raw string' to define file path in Python.

path = r"C:/Test.py"

However, a normal program may not have the permission to write in the C: drive root directory. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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