Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a file at a specific path?

Tags:

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.

like image 234
igferne Avatar asked Feb 24 '11 12:02

igferne


People also ask

How do I create a file in a specific directory?

To create a file inside a specific directory, we need to open a file using the absolute path. An absolute path contains the entire path to the file or directory that we need to use. It includes the complete directory list required to locate the file.

How do you create a file in a specific path in Python?

The besty practice is to use '/' and a so called 'raw string' to define file path in Python. However, a normal program may not have the permission to write in the C: drive root directory.


1 Answers

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.

like image 53
Shu Hikari Avatar answered Sep 30 '22 01:09

Shu Hikari