← Back to Python Course | Chapter 9: File Handling | Lesson 3 of 6

Python Writing Files

Writing a file is like writing in a notebook: you can start a fresh page or add to the end. Python saves your text so it is still there after the program stops.
Syntax
python
with open("file_name", "w") as file:  # "a" appends
    file.write("text")

Writing Text to Files

f.write(text) writes a string to an open file and returns the number of characters written -- opening a file in w mode first truncates any existing content, so writing to a file that already has data will completely replace it, not append to it.

Example: Writing Text to Files

python
with open("output.txt", "w") as f:
    f.write("first version")
with open("output.txt", "w") as f:
    f.write("replaced content")  # 'w' truncates first
with open("output.txt") as f:
    print(f.read())

Writing Multiple Lines

f.writelines(list_of_strings) writes multiple strings at once from any iterable, but unlike print() it does not add newlines between them automatically -- each string in your list needs its own trailing '\n' if you want them on separate lines.

Example: Writing Multiple Lines

python
lines = ["first\n", "second\n"]  # each string needs its own newline
with open("output.txt", "w") as f:
    f.writelines(lines)  # writelines does not add newlines automatically
with open("output.txt") as f:
    print(f.read())

Appending Data to Files

Opening a file with mode a instead of w preserves everything already in the file and writes new content starting at the end -- this is the mode you want for things like log files that should accumulate entries across many runs rather than being wiped each time.

Example: Appending Data to Files

python
with open("log.txt", "w") as f:
    f.write("run 1\n")
with open("log.txt", "a") as f:
    f.write("run 2\n")  # appended, run 1 is preserved
with open("log.txt") as f:
    print(f.read())

Writing Non-String Data

write() only accepts strings, so writing a number or a list directly raises a TypeError -- you need to convert it first with str(value) (or use json.dump() for structured data) before passing it to write().

Example: Writing Non-String Data

python
count = 42
with open("output.txt", "w") as f:
    f.write(str(count))  # write() only accepts strings, so count must be converted
with open("output.txt") as f:
    print(f.read())

Flushing Buffers

Python buffers written data in memory before actually pushing it to disk for performance reasons, which means data isn't necessarily saved the instant you call write() -- f.flush() forces an immediate write to disk, and closing the file (or exiting a with block) flushes automatically.

Example: Flushing Buffers

python
with open("output.txt", "w") as f:
    f.write("buffered data")
    f.flush()  # forces the buffered data to disk immediately
    print("Flushed to disk before the block even ends")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Opening with "w" when you meant to add data, which erases the existing file; use "a" to append.
  2. Passing a number to write(), as in f.write(42), which raises TypeError; convert with str(42).
  3. Forgetting \n, so write() calls end up joined on one line.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.