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? using python 3.3
Asked
Active
Viewed 8,232 times
2 Answers
6
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)

rakslice
- 8,742
- 4
- 53
- 57
-
2+1. But it's worth pointing out that you can't trust `__file__` after you've done anything that may have changed the working directory. If you're not sure what that means, do exactly what what this example does, call `abspath` and save it in a variable right at the very start, and then use that variable later. – abarnert May 08 '13 at 00:55
-
1Also, `print >> handle, "Hello world!"` is a `SyntaxError`. The OP is using Python 3.3. Try `print("Hello world!", file=handle)` instead. – abarnert May 08 '13 at 00:55
-
I receive a `FileNotFoundError` when opening an empty (or non-empty) file. Any suggestions here? – thedatastrategist Jan 19 '23 at 08:30
-
1@thedatastrategist When opening a file for writing, like this example, you don't get a `FileNotFound` error strictly because the file does not exist, but for other reasons, for instance if the directory you are trying to put it in no longer exists, or you don't have permission to see that it exists – rakslice Jan 19 '23 at 12:57
0
use open
:
open("folder_name/myfile.txt","w").close() #if just want to create an empty file
If you want to create a file and then do something with it, then it's better to use with
statement:
with open("folder_name/myfile.txt","w") as f:
#do something with f

Ashwini Chaudhary
- 244,495
- 58
- 464
- 504
-
doing `open(filename, 'w').close()` will truncate the file if file already existed and had any content. Using `open(filename, 'a').close()` is more safe. – Santosh Kumar Jul 23 '13 at 03:07