[python] 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.

This question is related to python

The answer is


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

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.


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