Reading & Writing Files
Open, read and write files using the with statement.
Syntax
with open('file.txt') as f:
data = f.read()Use the built-in open() function to work with files. The best practice is to wrap it in a with block, which automatically closes the file for you, even if an error happens.
Common modes
'r'— read (the default).'w'— write, replacing the file.'a'— append to the end.
Example
with open('notes.txt', 'w') as f:
f.write('First line\n')
f.write('Second line\n')
with open('notes.txt') as f:
for line in f:
print(line.strip())
# Output:
# First line
# Second lineWhen to use it
- A configuration loader reads a JSON settings file at startup and stores its contents in memory.
- A report exporter writes aggregated data rows to a CSV file on disk after processing.
- A log rotator opens a log file in append mode to add new entries without overwriting old ones.
More examples
Write text to a file
Opens a file in write mode using 'with', writes two lines, and closes it automatically.
with open('notes.txt', 'w') as f:
f.write('Line one\n')
f.write('Line two\n')
print('File written')Read a file line by line
Iterates over the file object to read one line at a time, stripping trailing whitespace.
with open('notes.txt', 'r') as f:
for line in f:
print(line.strip())
# Output:
# Line one
# Line twoAppend to an existing file
Opens the file in append mode ('a') so new content is added after existing content.
import datetime
entry = f"{datetime.datetime.now():%Y-%m-%d %H:%M} - App started\n"
with open('app.log', 'a') as f:
f.write(entry)
print('Log updated')
Discussion