…
…
Python Programming Fundamentals · Lesson 33 / 40 · Files
PreviewIn this lesson you will
with open(...), clean each line, split it into parts, and convert a part to a number"w" or "a") and with line endingsYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
When the program closes, every order entered during the day disappears. Ada wants every order written to a file, and the next day she wants that file read and the end-of-day summary produced. In this lesson you will learn to read and write text files and build the function that writes this summary to its own file.
Until now, all the data in your programs lived inside the program. The menu was in a dictionary and the orders were in a list of records. The moment the program ends, these values are erased from memory; when you run the program again the next day, nothing is left of yesterday's orders. For a café this is not acceptable: when Ada closes the register in the evening, she wants to know how many orders the day had, and the next morning she wants to look at yesterday's records.
The simplest way to make data permanent is to write it to a text file. A text file is made of plain writing: it opens in any program, like Notepad, and both people and Python can read it. The café has two files ready. menu.txt holds one item and its price on each line, and order-log.txt holds the day's orders in the format time;item;quantity. The brownie in the menu file is the large slice, $3.75.
Output08:40;tea;1
09:15;latte;2
10:05;brownie;1
12:30;latte;1
14:10;lemonade;2The function you will write at the end of the lesson, daily_summary("order-log.txt", "summary.txt"), will read this log, write the summary to the file summary.txt, and return two numbers. The returned value and then the summary file you read will look like this:
Output(5, 7)
Order count: 5
Total quantity: 7In this lesson you will:
with open(...) and close it safely.A note before you start: the exercises and code cells on this site run in your browser, in a virtual file system. Files such as menu.txt and order-log.txt are loaded ready-made with the exercise. The files you create exist only during that run and are deleted when you refresh the page. When you install Python on your own computer and run a program, files stay in the folder where the program runs and can be read again the next time.
open, with, and encodingTo work with a file, you first open it with the open function. open takes three pieces of information. The first is the name of the file, for example "menu.txt". The second is the mode: a single letter that says what you will do with the file. If you do not write a mode, Python assumes "r" (read). The third is encoding="utf-8": it tells Python which rule was used to encode the letters in the file.
| Mode | Meaning | If the file does not exist | If the file exists |
|---|---|---|---|
"r" | Read (default) | FileNotFoundError | Reads from the start, does not touch the content |
"w" | Write | Creates it | Erases the content, writes from the start |
"a" | Append | Creates it | Adds to the end of the existing content |
encoding="utf-8" looks like a small detail, but it matters for letters like é, ü, or ñ. Computers store letters as numbers, and which number a letter gets depends on the encoding. Because the default encoding can change with the operating system, the same file may look right on one computer and show broken characters, or even raise an error, on another. Writing encoding="utf-8" in every open call closes this problem from the start.
When you finish with an open file, it must be closed. In a file that is not closed, what you wrote may not be fully saved to the disk. To avoid forgetting this, Python uses the with statement:
with open("menu.txt", encoding="utf-8") as f: ...
This line opens the file and gives the file object the name f. You do the reading and writing with the methods of f. The moment the indented block ends, the file closes by itself. It closes even if the block is cut short by an error; you do not write this, with does it.
Once the door is closed, you cannot look inside. If you write f.read() outside the with block, Python gives this error:
OutputValueError: I/O operation on closed file.It means "input/output operation on a closed file". Everything you do with the file must be in the indented block. If you misspell the file name ("menu.text" instead of "menu.txt"), you get the error you know from lesson 32:
OutputFileNotFoundError: [Errno 2] No such file or directory: 'menu.text'Now let's read our first file. Each line in the menu looks like latte;4.25. When you clean the line and split it at the ; character, the item and the price separate:
Example 1 (case): Reading the menu line by line
with open("menu.txt", encoding="utf-8") as f: for line in f: item, price = line.strip().split(";") print(f"{item}: ${price}")
Outputlatte: $4.25
tea: $1.25
brownie: $3.75
lemonade: $3.25
water: $0.75On each turn the loop puts the next line of the file in the line box. strip() and split(";") are the string methods you know from lesson 21; the two parts are unpacked into the item and price boxes as in lesson 29. When the file ends, the loop stops, the block ends, and the file closes.
Let's reinforce the mode table. What does each mode do if the file already exists?
What does each mode do if the file already exists?
For each row, pick its match from the list, then check.
"r""w""a"\n and "everything is a string"There are several ways to read a file. They all give the same file; the difference is the pieces they hand it to you in:
| Way | What it gives | When |
|---|---|---|
f.read() | The whole file as one string | Seeing or printing a small file in one go |
f.readline() | Only the next line | Reading the first line (for example the header) separately |
f.readlines() | A list of all the lines | Knowing the number of lines, working with a list |
for line in f: | One line on each turn | The most common way; does not strain memory on a big file |
for line in f: walks through the file from start to end, one line at a time, and keeps only one line in memory at once. In a log of two million lines, f.read() loads the whole file into one string and f.readlines() loads it into a huge list; the loop processes the lines as they come. This is why the loop will be our default way in this lesson and the next ones.
Now let's get to the most important detail. Because we see the lines one under the other in a file, we forget that there is an invisible character at the end of every line: the newline character \n. When you read the line, this character comes with it. You cannot see it when you write print(line), because on the screen it only looks like moving to the next line. A good trick to see it is to print the line inside a list: when Python prints a list, it shows strings with their quotes and their hidden characters.
Example 2 (case): What is inside the first line?
with open("menu.txt", encoding="utf-8") as f: first = f.readline() print([first]) print(first == "latte;4.25", first.strip() == "latte;4.25")
Output['latte;4.25\n']
False TrueThe line you read is not "latte;4.25" but "latte;4.25\n". This is why the first comparison gives False; the two strings differ by one character. strip() removes the spaces at the start and the end, and \n with them; the cleaned line equals the expected string. Before running the code, try to predict:
The first line of menu.txt is latte;4.25. What does this code print?
with open("menu.txt", encoding="utf-8") as f: first = f.readline() print(first == "latte;4.25")
The second trap is this: everything you read from a file is a string. Just because menu.txt says 4.25, Python does not give it to you as a number; the line is the string "latte;4.25\n", and the price you get after splitting is the string "4.25". The rule we gave in lesson 4 holds here too: data that comes from outside almost always comes as a string. You must convert it with float() before doing math. If you forget the conversion, for example if you write total += price to add up the prices, Python gives this error:
OutputTypeError: unsupported operand type(s) for +=: 'int' and 'str'It means "+= cannot be used between int and str": total is a number, price is a string. A small detail: float("4.25\n") does not raise an error, because float drops the spaces and the \n around the number by itself. But "latte\n" == "latte" is still False. So the order is always the same: first strip(), then split(";"), and if you need math, float() or int().
Follow the code below step by step. The step-by-step view cannot open a file, so we imitated two lines with a list; in reality for line in f: gives exactly these lines, with the \n at their ends. At each step, look at the line, item, and price boxes: at which step does the \n disappear? Is the value in the price box with quotes or without? What type are the values in the menu dictionary?
Run the code line by line: see which line runs next, the variable boxes and the output.
lines = ["latte;4.25\n", "tea;1.25\n"] menu = {} for line in lines: item, price = line.strip().split(";") menu[item] = float(price) print(menu)
The \n is in the line box; after strip() it is not in the split parts. price is still the string '4.25'; as it goes into the dictionary, float() converts it to the number 4.25. The dictionary is now ready for math.
It is also very common to use only some of the parts in a line. Each line in the log has three parts; to find the total quantity of latte orders, we do not use the time, we check the item, and we add up the quantity:
Example 3 (case): Latte quantity from the log
latte = 0 with open("order-log.txt", encoding="utf-8") as f: for line in f: time, item, quantity = line.strip().split(";") if item == "latte": latte += int(quantity) print("Latte quantity:", latte)
OutputLatte quantity: 3There are two latte lines in the log: 2 at 09:15, 1 at 12:30. Even without strip(), item would come out right (the last part is the quantity), but if the part we compare were at the end of the line, "latte\n" == "latte" would not match and no line would be counted. Make it a habit: strip() first on every line.
Your turn. The cell below first writes its own small file, then reads it. Run it, then try the three tasks at the top in order.
Try it now· not graded; doesn't affect progress
"w", "a", and writeWe have seen reading; now let's move to writing, Ada's real request. To write, you open the file with the "w" or "a" mode and write with f.write(text). The difference between the two modes is very important. The "w" mode erases the old content the moment it opens the file, before you write a single line. This is right for a report that is made from scratch each time: you want today's summary to replace yesterday's. The "a" mode keeps the old content and adds what you write to the end. This is the right mode for an order log that grows through the day or a record file that grows through the year.
The write method has two rules. The first is that it takes only strings. If you write f.write(85), you get this error:
OutputTypeError: write() argument must be str, not intTo turn a number into a string, you use str(85) or an f-string. The second is that write does not move to a new line. print moves to the next line after each call; write does not, and the text you write is added to the file as it is. For each record to be on its own line, you must put \n at the end of the text. The pattern that solves both rules in one move is the f-string: f.write(f"{time};{item};{quantity}\n"). Numbers turn into strings inside the f-string, and the \n at the end finishes the line.
Example 4 (case): Writing and reading again
with open("daily.txt", "w", encoding="utf-8") as f: f.write("09:15;latte;2\n") f.write("10:05;brownie;1\n") with open("daily.txt", encoding="utf-8") as f: print(f.read(), end="")
Output09:15;latte;2
10:05;brownie;1The first with block creates the file, writes two lines, and closes. The second block opens the same file in read mode; f.read() gives the whole content as one string. We wrote end="" because the last line of the file already ends with \n; if print added one more, an empty line would be left at the bottom.
Now let's see the power of "w". The same file is opened twice, both times with "w". Read the code and predict:
What does this code print?
with open("daily.txt", "w", encoding="utf-8") as f: f.write("09:15;latte;2\n") with open("daily.txt", "w", encoding="utf-8") as f: f.write("10:05;brownie;1\n") with open("daily.txt", encoding="utf-8") as f: print(f.read(), end="")
Run the same code with three different modes and see the difference with your own eyes. Below, the mode of the second open is in the mode variable:
Change the mode of the second opening. What is left in the file? What happens when you choose "r"?
Pick a value; predict the output first, then look.
1with open("daily.txt", "w", encoding="utf-8") as f:2 f.write("09:15;latte;2\n")3mode = "w"4with open("daily.txt", mode, encoding="utf-8") as f:5 f.write("10:05;brownie;1\n")6with open("daily.txt", encoding="utf-8") as f:7 print(f.read(), end="")
10:05;brownie;1
Faded lines didn't run with this value. "w" erases the first line, and only the brownie is left in the file. "a" keeps the first line and adds the brownie below it. A file opened with "r" cannot be written to: Python raises a not writable error and never reaches the reading line.
The error on the "r" button also teaches something: you cannot write to a file you opened in read mode. Python shows the full name of the error as io.UnsupportedOperation: not writable. If you will write, you must give the mode explicitly as "w" or "a"; not writing a mode means "r".
Now you have all the parts of the program Ada wants. The program does three jobs: it keeps two counters while reading the log, then writes these numbers to the summary file, and finally returns the numbers. Which mode for the summary file? The summary is a report made from scratch on each run; today's should replace yesterday's, not be added below it. So "w". We also return the numbers for testing: as in lesson 19, you can write assert daily_summary(...) == (5, 7) and test the function in a single line.
Example 5 (case): The lesson's target program
def daily_summary(source, target): # 1. Prepare the counters orders = 0 total_quantity = 0 # 2. Read the log line by line with open(source, encoding="utf-8") as f: for line in f: time, item, quantity = line.strip().split(";") orders += 1 total_quantity += int(quantity) # 3. Write the summary with open(target, "w", encoding="utf-8") as f: f.write(f"Order count: {orders}\n") f.write(f"Total quantity: {total_quantity}\n") # 4. Return the result return orders, total_quantity print(daily_summary("order-log.txt", "summary.txt")) with open("summary.txt", encoding="utf-8") as f: print(f.read(), end="")
Output(5, 7)
Order count: 5
Total quantity: 7Two with blocks come one after the other, and both use the name f; this is not a problem, because the first file is already closed before the second block starts. Notice the indentation of the second block: it is not inside the reading block, it is at the same level. The writing job is done once, after the reading ends. return orders, total_quantity returns two values as a tuple, as in lesson 29; print writes it as (5, 7).
Put the reading and writing parts of the target program in the right order. The indentation is a clue too: which line is inside which block?
Put the lines that read the log and write the summary in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The same pattern is useful outside the café too. Imagine you keep your reading list in a file: on each line, the title of a book and its number of pages. First let's write the file, then read it and find the total pages:
Example 6 (outside the case): Reading list
with open("reading.txt", "w", encoding="utf-8") as f: f.write("Short Stories;180\n") f.write("Travel Notes;96\n") f.write("Garden Guide;160\n") pages = 0 with open("reading.txt", encoding="utf-8") as f: for line in f: book, count = line.strip().split(";") pages += int(count) print("Pages read:", pages)
OutputPages read: 436The book titles have spaces; because we split at ;, the spaces are not a problem. Let's now see the error messages you meet when working with files, all together. Match each message to its cause:
Match each error message to its most likely cause.
For each row, pick its match from the list, then check.
TypeError: write() argument must be str, not intFileNotFoundError: ... 'menu.text'TypeError: unsupported operand type(s) for +=: 'int' and 'str'ValueError: not enough values to unpackValueError: I/O operation on closed file.The most common mistake when writing to a file is forgetting \n. Because you are used to writing with print, you think write will move to the next line too:
with open("items.txt", "w", encoding="utf-8") as f: f.write("latte") f.write("tea") with open("items.txt", encoding="utf-8") as f: print(f.read())
OutputlatteteaThe two items joined in one line. If you read this file line by line the next day, you get a single line, lattetea; the two items are lost. The fix is simple: \n at the end of every record. When you write f.write("latte\n") and f.write("tea\n"), there are two separate lines in the file.
One last note: in real files, empty lines can sneak in, especially if a person edited the file by hand. On an empty line, line.strip() gives an empty string, split(";") returns a single part, and trying to unpack it into three boxes raises ValueError: not enough values to unpack. You skip empty lines at the start of the loop with the continue from lesson 11: if line.strip() == "": continue. This pattern will help you in the last exercise.
Combined with the try–except from lesson 32, you get a loader that does not crash when the file is missing.
def load_menu(file_name): menu = {} try: with open(file_name, encoding="utf-8") as f: for line in f: item, price = line.strip().split(";") menu[item] = float(price) except FileNotFoundError: print("File not found:", file_name) return menu print(load_menu("menu.txt")) print(load_menu("menu.text"))
Output{'latte': 4.25, 'tea': 1.25, 'brownie': 3.75, 'lemonade': 3.25, 'water': 0.75}
File not found: menu.text
{}The "a" mode keeps the old records on every call; the log grows day by day.
def add_steps(file_name, day, steps): with open(file_name, , encoding=) f: f.write(f) add_steps(, , 6200) add_steps(, , 8100) add_steps(, , 4700) total = 0 (, encoding=) f: line f: day, steps = line.strip().split() total += (steps) (, total)
Opening an existing log with `"w"`. If you write open("order-log.txt", "w", ...) to save each new order during the day, every record erases the one before it; in the evening only the last order is left in the file. "w" empties the file the moment it opens it; it does not add to the end. The right way: use "a" for growing files, open("order-log.txt", "a", encoding="utf-8"), and keep "w" only for files that are made from scratch each time (for example the end-of-day summary).
A sneakier form of the same mistake is writing "w" out of habit when you only want to read the file. To look at yesterday's log in the morning, Ada runs this:
with open("order-log.txt", "w", encoding="utf-8") as f: for line in f: print(line.strip())
OutputTraceback (most recent call last):
File "<code>", line 2, in <module>
for line in f:
^
io.UnsupportedOperation: not readableThe last line of the error message says "not readable": a file opened with "w" is only for writing, and you cannot read lines from it. (The io. prefix says the error comes from the part of Python that handles file work; in lesson 36 we will call such parts modules.) The real bad news is not in the message: the error came on line 2, but the
with open(name, mode, encoding="utf-8") as f: opens the file and closes it when the block ends, even if there is an error; "r" reads, "w" erases the content and writes from the start, "a" adds to the end.for line in f: reads the file line by line; every line has a \n at the end and everything you read is a string: first strip(), then split(";"), and for math int() or float().write takes only strings and does not move to a new line; write with an f-string and add \n at the end of every record.Next lesson: The lines we used had fields separated by ;; real tables are separated by commas, and a field can contain a comma. In the next lesson we will use the csv module for this.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputSteps in three days: 19000open(..., "w")"r"open("order-log.txt", encoding="utf-8")"w"