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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With