Python File Handling

Python Write/Create Files

Writing to files

Python Write/Create Files

To write to an existing file, you must add a parameter to the open() function.

Write to File

f = open("demofile2.txt", "w")
f.write("Hello! Welcome to Python file handling.")
f.close()

Append to File

f = open("demofile2.txt", "a")
f.write("\nThis is a new line.")
f.close()

Create New File

f = open("myfile.txt", "x")
f.write("This is a new file.")
f.close()