Reputation: 1229
I'm practicing the management of .txt files in Python. I've been reading about it and found that if I try to open a file that doesn't exist yet it will create it on the same directory from where the program is being executed. The problem comes that when I try to open it, I get this error:
IOError: [Errno 2] No such file or directory:
'C:\Users\myusername\PycharmProjects\Tests\copy.txt'.
I even tried specifying a path as you can see in the error.
import os
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'copy.txt')
Upvotes: 103
Views: 351622
Reputation: 2909
I'd like to give not an answer, but a general tip on creating files with Python in the home dir:
Do not use '~/myfile' to create "myfile" in the home dir. Use expanded '/home/user/myfile' or Python will give you a similar error. I came to this post exactly because of this problem.
Upvotes: 1
Reputation: 9766
Looks like you forgot the mode parameter when calling open
, try w
:
with open("copy.txt", "w") as file:
file.write("Your text goes here")
The default value is r
and will fail if the file does not exist
'r' open for reading (default)
'w' open for writing, truncating the file first
Other interesting options are
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
See Doc for Python 2.7 or Python 3.6
Upvotes: 209
Reputation: 637
# Method 1
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name) # Write inside file
f.close() # Close file
# Method 2
with open("Path/To/Your/File.txt", "w") as f: # Opens file and casts as f
f.write("Hello World form " + f.name) # Writing
# File closed automatically
There are many more methods but these two are most common. Hope this helped!
Upvotes: 18