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 exists 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:UsersmyusernamePycharmProjectsTestscopy.txt’.
I even tried specifying a path as you can see in the error.
JavaScript
x
4
1
import os
2
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
3
my_file = os.path.join(THIS_FOLDER, 'copy.txt')
4
Advertisement
Answer
Looks like you forgot the mode parameter when calling open
, try w
:
JavaScript
1
3
1
with open("copy.txt", "w") as file:
2
file.write("Your text goes here")
3
The default value is r
and will fail if the file does not exist
JavaScript
1
3
1
'r' open for reading (default)
2
'w' open for writing, truncating the file first
3
Other interesting options are
JavaScript
1
3
1
'x' open for exclusive creation, failing if the file already exists
2
'a' open for writing, appending to the end of the file if it exists
3