Chapter 13: Writing Files with Open
Learn how to create, overwrite, and append data to external files in Python! Master write access modes ('w' and 'a'), write multi-line text arrays, and stream data across files to perform automated file copying.
Why Writing to Files is Essential in Data Science
After performing data analysis, filtering datasets, or training machine learning models in memory, you need to persist your results so they can be saved permanently on disk or shared with other tools. Python's open() function with write or append modes enables you to export structured output, write audit logs, and save generated reports.
13.1 Writing Modes: 'w' (Overwrite) vs 'a' (Append)
When opening a file for writing, choosing the correct mode is critical:
# 1. Overwrite mode ('w')
with open("Example2.txt", "w") as f:
f.write("Line A\n")
# 2. Append mode ('a')
with open("Example2.txt", "a") as f:
f.write("Line B\n")
# Read results to check
with open("Example2.txt", "r") as f:
print(f.read())
Try Writing Modes: Click "Try It Yourself" to run this write and append block. Notice how the file first gets created and written with "Line A", and then "Line B" is appended to it without overwriting.
'w' Mode (Write / Overwrite)
Creates a new file if it doesn't exist. WARNING: If the file already exists in your directory, opening it with 'w' instantly erases and overwrites all existing content!
'a' Mode (Append)
Opens the file for appending. It preserves existing file data and positions the writing cursor at the very end of the file to add new lines without destroying past records.
Type text to write to Example2.txt. Switch between 'w' (Overwrite) and 'a' (Append) modes to see how disk storage changes.
13.2 Writing Text & Lists (write & Newline \n)
When calling file.write("text") in Python, notice that Python does not automatically append a newline character at the end of your string. If you call write() twice successively without adding \n, the text will be concatenated on the exact same line!
with open("Example2.txt", "w") as file1:
file1.write("This is line A\n") # Explicit \n creates newline
file1.write("This is line B\n")
# Verify content by reading back
with open("Example2.txt", "r") as f:
print(f.read())
Writing Lists of Strings
To write multiple items from a list, iterate through the list using a for loop:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("Example2.txt", "w") as file1:
for line in lines:
file1.write(line)
# Verify content by reading back
with open("Example2.txt", "r") as f:
print(f.read())
Add strings to a list in memory, then execute a for loop to write each list item into Example2.txt on disk.
13.3 Copying Files (Reading from Source & Writing to Target)
A common file handling workflow in Python is copying contents from an existing source file into a new destination file. You can open both files simultaneously using nested with context managers:
# Copy contents of Example1.txt to Example3.txt
with open("Example1.txt", "r") as readFile:
with open("Example3.txt", "w") as writeFile:
for line in readFile:
writeFile.write(line)
# Verify copied contents
with open("Example3.txt", "r") as f:
print(f.read())
How it works:
readFileopensExample1.txtin Read mode ('r').writeFileopensExample3.txtin Write mode ('w').- The
for line in readFile:loop streams lines one by one from the source file and writes each line into the target file. - At the end of the loop, both context managers automatically close both file handles!
Step through the file copy loop to see line data streaming from read_file (Source) into write_file (Target).
Practice Quiz
Validate your understanding of write modes, append behavior, line writing, and file copying in Python.