Reading and writing files

INPUT · Slides

Open a file and read it

01 / 07

Everything vanished when the run ended

Every variable, list and dictionary you have built so far shares one weakness: when the program ends, the contents go with it.

Write a program that keeps a shopping list and the next run starts blank again. That is no use as a list.

The first way past this is a file. Put some text outside the program and it survives the run. A notes app, a budget tracker, a game's save data — at the root, all of them are this.

02 / 07

The file area in this course

One thing to know first: file work here happens in a made-up area inside your browser. It never touches the real files on your device, so try things freely.

The trade is that the area is rebuilt on every run. So throughout this chapter you always write something out yourself before you read it — out and back, inside a single run.

To write, hand open a "w". The w is for write. We cover it properly in the next group; for now treat it as getting ready to read.

f = open("memo.txt", "w")f.write("morning")f.close()print("written")

Result

written

03 / 07

Open, read, close

Reading takes three steps and no more.

  • open("memo.txt") … opens the file. Leave the mode off and you get reading
  • f.read() … hands you the contents as one single string
  • f.close() … closes it

What read gives back is a string. So put it in a variable and handle it exactly as you always have.

f = open("memo.txt", "w")f.write("morning")f.close()f = open("memo.txt")text = f.read()f.close()print(text)

Result

morning

04 / 07

Forget to close and nothing is there

Why close at all? Because what you wrote may not have reached the file area until you do.

The example below leaves f.close() until later and opens the file again in the meantime. The number of characters read is 0. Close it and read again and all seven are there.

It is not finished until it is closed.

f = open("memo.txt", "w")f.write("morning")f2 = open("memo.txt")print(len(f2.read()))f2.close()f.close()f3 = open("memo.txt")print(len(f3.read()))f3.close()

Result

0
7

05 / 07

The newline on the end of what you read

If there is a newline in the file, the string read gives you keeps that newline on the end. Then print adds one of its own, so you get a stray blank line.

There are two ways to be rid of it.

  • print(text, end="") … stop print adding its newline
  • print(text.strip()) … drop the whitespace and newlines from both ends first
f = open("memo.txt", "w")f.write("morning\nnoon\n")f.close()f = open("memo.txt")text = f.read()f.close()print(text, end="")

Result

morning
noon

06 / 07

Open a file that is not there and it stops

Try to read a file that does not exist and Python raises FileNotFoundError and stops there. One of the errors you met in Chapter 4.

You get it when you mistype a name, too. A file that is not there does not get made — you get an error — and that is the rule in reading mode.

f = open("missing.txt")print(f.read())

Result

FileNotFoundError: [Errno 44] No such file or directory: 'missing.txt'

07 / 07

Summary

Reading a file went like this.

  • open to open it
  • read to take the contents as a string
  • close to close it

But you may have noticed the catch. Forget the close and you are undone. Even in these examples the line count crept up each time you opened something. The more lines there are, the easier it is to forget — and if an error happens partway, you never reach the close at all.

Next lesson you learn a way of writing that makes forgetting structurally impossible.