Creating A Python File In A Local Directory
Okay so I'm basically writing a program that creates text files except I want them created in a folder that's in this same folder as the .py file is that possibly? how do I do it?
Solution 1:
To find the the directory that the script is in:
import os
path_to_script = os.path.dirname(os.path.abspath(__file__))
Then you can use that for the name of your file:
my_filename = os.path.join(path_to_script, "my_file.txt")
with open(my_filename, "w") as handle:
print("Hello world!", file=handle)
Solution 2:
use open
:
open("folder_name/myfile.txt","w").close() #if just want tocreate an empty file
If you want to create a file and then do something with it, then it's better to use with
statement:
withopen("folder_name/myfile.txt","w") as f:
#do something with f
Post a Comment for "Creating A Python File In A Local Directory"