Write Files
Python · File Handling
Theory
Opening a file with mode 'w' prepares it for writing text. If the file does not exist it is created; if it already exists, its contents are erased immediately when the file is opened, before you write anything. f.write(text) writes a string and returns the number of characters written. It does not add a newline for you, so include '\n' yourself, and it only accepts strings, so convert numbers with str() or an f-string.
f.writelines(list_of_strings) writes several strings in one call. Written data is buffered in memory and flushed to disk when the file is closed, which the with statement does for you. A common safe pattern is to write a report: with open('report.txt', 'w') as f: f.write(f'Total sales: {total}\n'). Use mode 'x' instead of 'w' if you want an error rather than an overwrite when the file already exists.
Why we use it
Programs need to save their results - reports, cleaned data, logs and exports - so other people and programs can use them after the script finishes.
When to use it
Use 'w' when you want to create or fully replace a file's content. To add to an existing file use 'a'; to save a DataFrame, df.to_csv() or df.to_excel() is simpler than writing lines by hand.
How it works
- with open('report.txt', 'w') as f:
- Does report.txt exist? Yes: Erase its content (truncate). No: Create a new empty file.
- f.write('Total sales: 5000')
- Data sits in a buffer in memory
- Block ends: buffer flushed, file closed
Syntax
with open('file.txt', 'w') as f:
f.write(text)Example
with open('report.txt', 'w') as f:
f.write('Total sales: 5000')Key points
- 'w' mode erases any existing file content first
- Always closes the file safely when used with with
- write() needs strings and does not add '\n'
- Mode 'x' fails instead of overwriting an existing file
- For DataFrames use df.to_csv() instead of manual writes