livepython.net
CHAPTER 19File Handling
19.2  WRITE

Python Write to File: write() and Append Mode

Write to a File with write()

The write() method puts text into a file that's open in mode "w" or "a". It writes exactly the string you give it, nothing more.

Think of it like writing in a notebook with a pen. Only the words you write end up on the page. The notebook doesn't add a full stop, a space or a new line for you.

The rules

  • f.write(text) takes one string.
  • It writes nothing on the screen. To see the text, read the file back.
  • Numbers must become text first: str(25), or an f-string like f"{score}" (chapter 5).
  • You can call write() many times before you close the file. Each call carries on where the last one stopped.
PYTHONedit me
name = "Sunny"
score = 92

f = open("result.txt", "w")
f.write(name)
f.write(" scored ")
f.write(str(score))
f.close()

f = open("result.txt")
print(f.read())
f.close()
OUTPUT
Sunny scored 92

Three write() calls, one line of text: each piece goes right after the one before.

Avoid: writing a number

PYTHONedit me
f = open("result.txt", "w")
f.write(92)
f.close()
OUTPUT
TypeError: write() argument must be str, not int

Don't worry, the message tells you the fix. write() wants a str (a string), and you gave it an int.

Good: turn it into text first

PYTHONedit me
score = 92

f = open("result.txt", "w")
f.write(f"Score: {score}")
f.close()

f = open("result.txt")
print(f.read())
f.close()
OUTPUT
Score: 92

An f-string builds the whole text in one go, with the number inside. That's usually the neatest way.

Common beginner doubt: "print() takes many values with commas. Does write()?" No. f.write("Sunny", "Rocky") gives a TypeError. Join the pieces into one string first, with + or an f-string.

write() puts one string into the file, exactly as you give it. Turn numbers into text first.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnPredict the output

What will this print?

f = open("word.txt", "w") f.write("Live") f.write("Python") f.close() f = open("word.txt") print(f.read()) f.close()
Your turn! What will this code show on the screen?

Write Lines to a File: Add the Newline Yourself

To write lines to a file, end each one with the newline character "\n", the escape sequence from chapter 2. print() starts a new line for you; write() never does.

Think of it like an old typewriter. It keeps typing on the same line until you press the Return key yourself. In a file, "\n" is that key.

The rules

  • Add "\n" at the end of every line you write: f.write("Sunny\n").
  • Joining works too: f.write(name + "\n"), or inside an f-string: f.write(f"{name}\n").
  • To write a whole list, loop over it and write one line per item.

Avoid: no newline

PYTHONedit me
f = open("names.txt", "w")
f.write("Sunny")
f.write("Rocky")
f.write("Lucky")
f.close()

f = open("names.txt")
print(f.read())
f.close()
OUTPUT
SunnyRockyLucky

Three names, all squashed into one word. Nothing went wrong, as far as Python can tell: it wrote exactly what it was given.

Good: one name per line

PYTHONedit me
f = open("names.txt", "w")
f.write("Sunny\n")
f.write("Rocky\n")
f.write("Lucky\n")
f.close()

f = open("names.txt")
print(f.read())
f.close()
OUTPUT
Sunny
Rocky
Lucky

Write a list with a loop

With a for loop from chapter 10, a list of any length becomes a file with one item per line:

PYTHONedit me
fruits = ["apple", "banana", "cherry"]

f = open("fruits.txt", "w")
for fruit in fruits:
    f.write(fruit + "\n")
f.close()

f = open("fruits.txt")
print(f.read())
f.close()
OUTPUT
apple
banana
cherry

The open() and close() are outside the loop: open once, write many lines, close once.

Common beginner doubt: "Why does the output end with an empty line?" The last "\n" ends the last line, and print() adds its own new line after it. Most files end with a "\n" like this. It's normal, and you'll learn to tidy it with strip() when you read files.

write() never adds a new line. End every line with "\n" yourself.

your turnFill the gap

Put each city on its own line

cities = ["Delhi", "Paris"] f = open("cities.txt", "w") for city in cities: f.write(city + ?) f.close() f = open("cities.txt") print(f.read()) f.close()

It should print: Delhi Paris

Which piece makes this code work?
your turnType the output

Type what this prints

f = open("count.txt", "w") for n in range(1, 4): f.write(str(n) + "\n") f.close() f = open("count.txt") print(f.read()) f.close()
Read the code line by line, then type the output exactly.

Write Mode Replaces the Whole File

Opening a file in mode "w" empties it first. Everything that was in it is gone, and your writing starts on a blank page. This happens the moment you call open(), before you write a single letter.

Think of it like a whiteboard. Before each lesson, the teacher wipes it clean, then writes the new notes. Yesterday's notes don't come back.

The rules

  • "w" on a file that exists: the old text is deleted.
  • "w" on a file that doesn't exist: a new, empty file is made.
  • That's why "w" is perfect for saving: the file always holds the latest version, nothing older.
PYTHONedit me
f = open("best.txt", "w")
f.write("Best: Sunny, 80 points")
f.close()

f = open("best.txt", "w")
f.write("Best: Rocky, 95 points")
f.close()

f = open("best.txt")
print(f.read())
f.close()
OUTPUT
Best: Rocky, 95 points

Rocky beat Sunny's score, and the file only keeps the new best. Exactly what you want for a "best score" file.

Avoid: opening with "w" inside a loop

PYTHONedit me
names = ["Sunny", "Rocky", "Lucky"]

for name in names:
    f = open("team.txt", "w")
    f.write(name + "\n")
    f.close()

f = open("team.txt")
print(f.read())
f.close()
OUTPUT
Lucky

Each turn of the loop opens the file with "w" again, and wipes the name written before. Only the last one, Lucky, survives.

Good: open once, before the loop

PYTHONedit me
names = ["Sunny", "Rocky", "Lucky"]

f = open("team.txt", "w")
for name in names:
    f.write(name + "\n")
f.close()

f = open("team.txt")
print(f.read())
f.close()
OUTPUT
Sunny
Rocky
Lucky

Common beginner doubt: "Does Python ask before it empties a file?" No, never. There's no warning and no undo. On your own computer, double-check the file name before you open a file with "w".

Mode "w" wipes the file the moment it opens. Open it once, then write everything.

your turnPredict the output

What will this print?

f = open("day.txt", "w") f.write("Monday") f.close() f = open("day.txt", "w") f.close() f = open("day.txt") print(len(f.read())) f.close()
Your turn! What will this code show on the screen?
your turnFix the code

Fix the code so all three colours are saved

It should print: red green blue

colours = ["red", "green", "blue"]
for colour in colours:
    f = open("colours.txt", "w")
    f.write(colour + "\n")
    f.close()
f = open("colours.txt")
print(f.read())
f.close()
This code does not work yet. Fix it, then press Run.

Append to a File with Mode a

Append mode, "a", adds new text at the end of a file and keeps everything already in it. If the file doesn't exist yet, Python makes it.

Think of it like a diary. Every evening you open it at the next empty page and write today's entry. You never tear out the old days.

"w" or "a"?

"w" (write)"a" (append)
Old textdeletedkept
New text goesat the start of an empty fileafter the old text
Good forsaving the latest versionlogs, diaries, lists that grow

"a" doesn't add a new line either. End every line with "\n", as before.

PYTHONedit me
f = open("diary.txt", "w")
f.write("Monday: learned lists\n")
f.close()

f = open("diary.txt", "a")
f.write("Tuesday: learned loops\n")
f.close()

f = open("diary.txt", "a")
f.write("Wednesday: learned files\n")
f.close()

f = open("diary.txt")
print(f.read())
f.close()
OUTPUT
Monday: learned lists
Tuesday: learned loops
Wednesday: learned files

The first open() uses "w" to start a fresh diary. The next two use "a", so each entry lands under the last one.

Why start with "w"?

With only "a", every run of a program adds its lines again. This loop plays three runs of the same program:

PYTHONedit me
f = open("log.txt", "w")
f.close()

for run in range(3):
    f = open("log.txt", "a")
    f.write("Program started\n")
    f.close()

f = open("log.txt")
print(f.read())
f.close()
OUTPUT
Program started
Program started
Program started

For a real log, that's what you want: one line per run. But examples in this course should print the same thing every time, so they start each file fresh with "w" first.

Common beginner doubt: "Can append mode add a line at the top, or in the middle?" No. "a" always writes at the very end. To change the middle, read the whole file, change the text, and write it all back with "w".

Mode "a" adds to the end and keeps the old text. Mode "w" starts over.

your turnType the output

Type what this prints

f = open("shop.txt", "w") f.write("milk\n") f.close() f = open("shop.txt", "a") f.write("eggs\n") f.close() f = open("shop.txt") print(f.read()) f.close()
Read the code line by line, then type the output exactly.
your turnPredict the output

Remember default values?

def greet(name, greeting="Hello"): return greeting + ", " + name print(greet("Rocky"))
Your turn! What will this code show on the screen?

Practice: Write

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 172.Python Program to Write a Shopping List to a FileEasySolve
  2. 173.Python Program to Append Entries to a Diary FileMediumSolve