Skip to content
Advertisement

How to create a new text file using Python

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

Advertisement

Answer

Looks like you forgot the mode parameter when calling open, try w:

JavaScript

The default value is r and will fail if the file does not exist

JavaScript

Other interesting options are

JavaScript

See Doc for Python2.7 or Python3.6

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement