igferne
igferne

Reputation: 339

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.

Upvotes: 27

Views: 164945

Answers (8)

Sadman Sakib
Sadman Sakib

Reputation: 11

Use os module

filename = "random.txt"

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

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

Upvotes: 0

Shu Hikari
Shu Hikari

Reputation: 397

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.

Upvotes: 26

Bite code
Bite code

Reputation: 596753

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.

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375584

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"

Upvotes: 26

Wipqozn
Wipqozn

Reputation: 1314

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.

Upvotes: 1

TyrantWave
TyrantWave

Reputation: 4673

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

Upvotes: 1

kurumi
kurumi

Reputation: 25599

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

Upvotes: 3

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

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.

Upvotes: 3

Related Questions