Back to course

File Handling 3: Writing and Appending Files

Python Programming: The 0 to Hero Bootcamp

Writing to Files

1. Write Mode ('w')

If the file exists, writing in 'w' mode will erase all its current contents. If the file does not exist, it will be created.

Use the .write(string) method.

python file_name = 'output.txt'

with open(file_name, 'w') as f: f.write("First line of output.\n") f.write("Second line, written over the old content.\n") f.write(str(12345) + '\n') # Remember to cast non-strings

If you open output.txt, it only contains the three lines above.

2. Append Mode ('a')

If the file exists, data is added to the end. If it doesn't exist, a new file is created.

python with open(file_name, 'a') as f: f.write("\n--- Appended Data ---\n") f.write("This line is added to the end.\n")

If you open output.txt, the appended data is at the bottom.

The writelines() Method

Used to write a sequence of strings (like a list of lines) to the file. Note: It does not automatically add newlines; you must include them in the strings.

python lines_to_write = [ "Item 1\n", "Item 2\n", "Item 3\n" ]

with open('items.txt', 'w') as f: f.writelines(lines_to_write)