How to create a new text file using Python

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 Python2.7 or Python3.6

Leave a Comment