Python Write/Create Files

Python Write/Create Files

To write to an existing file, you must add a parameter to the open() function. You can either append content to the end of the file or completely overwrite it.


1. Writing to an Existing File

Append Mode ("a")

Using "a" will add text to the existing file without erasing what's already there.

Append Example

// Open the file and append a line
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

// Open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read())

Write/Overwrite Mode ("w")

Using "w" will completely erase the old content and replace it with your new content.

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

2. Create a New File

To create a new file in Python, use the open() method with one of the following parameters:

# Create a brand new, empty file
f = open("myfile.txt", "x")

Exercise

?

Which mode should you use to add text to the end of a file without destroying the current text?