←
Class 12 Computer Science
2. File Handling in Python · 2 / 13
⌕
Chapter 2 of 13

2. File Handling in Python

11 sections · 9,389 words

Opening

286 words · 1 min read

Big idea: A file lets a program remember information after the program ends.

Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.

  • Distinguish a variable, which forgets at once, from a file, which keeps data later.
  • Explain what a path is and which folder a relative path is measured from.
  • Distinguish text files from binary files and choose between them for a task.
  • Open files with a suitable mode and close them safely with with.
  • Write text with write and writelines, supplying your own newline characters.
  • Read files with read, readline, readlines and a for loop, and tell blank lines from the end of a file.
  • Move the read position with tell and seek, and explain what an offset counts.
  • Store records in a text file, read them back, and save objects with pickle safely.

Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.

This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.

Complete Python examples have Copy code and an external run link. First predict the output. Run the example, then change one input and explain what changed. The output box shows the expected result; it is not another program.

File examples use an external Python playground because Python Tutor does not provide ordinary file access. Copy the complete example before opening it. The playground files are temporary browser files, separate from files on your computer.

2.1 INTRODUCTION TO FILES

967 words · 4 min read

A list in a running program is useful while that program is alive. If you want the next session to read the same information, you need to save it. A file is one way to keep the data between runs.

The file has a location, described by its path. Opening it gives the program a file object through which it can read or write. The object and the stored file are related, but they are not the same thing.

  1. Choose where the file should live.
  2. Open a connection to it with a mode matching the task.
  3. Read or write through that connection, then close it.
In simple words: A filename without its location can be ambiguous. Check the working directory before deciding a file is missing.

A game saves your progress when you close it. Tomorrow it starts where you stopped.

A program without files starts from zero every time, and nothing it calculated survives. This section shows what a file is and how a program reaches one.

A variable lives in memory while one program runs. When the program ends, the memory is released and every variable is gone.

A file is a named collection of bytes kept on a storage device. Files stay in place when the program ends, and even when the computer is switched off.

A saved file keeps its data after the program ends. That single difference explains why every serious program stores something.

A game keeps your level. A notes app keeps your pages.

A study tracker keeps your minutes.

A path tells the operating system which stored file you mean. A name such as "diary.txt" is a relative path.

The system measures it from the working directory, the folder the program runs in. An absolute path starts from the top of the filesystem, such as /home/student/diary.txt or C:\Users\Student\diary.txt.

A relative path can point somewhere other than you expect. The working directory follows the place the program was started from, not the folder holding the script. Check it whenever a file seems to disappear.

To reach a file, a program opens it. Opening creates a file object, also called a file handle.

The handle is the program’s connection to the stored bytes. It is not the file itself, just as a library card gives access to a book without being the book.

Working through the handle follows four steps: open with a mode, read or write, then close. Closing releases the connection and completes any pending internal work. The sections ahead take one step at a time.

Choose a path and modeOpen a streamRead or write dataClose the stream
A with statement manages the stream lifetime, including ordinary exception exits.

Read the diagram. The four boxes show one file journey in order. The first box collects two decisions: the path and the mode. The second box is the open call, which returns the handle. The third box does the real work through that handle. The last box closes it. Every example in this chapter follows these boxes in the same order.

Write down what this program should print before you read the expected output.

with open("diary.txt", "w", encoding="utf-8") as stream:
    stream.write("day 1: learned about files")
with open("diary.txt", encoding="utf-8") as stream:
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 1 opens diary.txt for writing. The file does not exist yet, so Python creates it.
  2. Line 2 writes one line of text. The string holds no newline character at the end.
  3. The with block ends after line 2, so the writer closes and the text is safely stored.
  4. Line 3 opens the same path again, this time for reading.
  5. Line 4 reads the whole file and prints it.

Output
day 1: learned about files

Add a second write call on a new line inside the first with block. Predict whether the two texts sit side by side or on separate lines.

The example created the file because it was missing. Reading behaves differently: a missing path stops the program.

Save this program as show.py and run it in an empty practice folder.

Python
stream = open("scores.txt")
print(stream.read())
Output
Traceback (most recent call last):
  File "show.py", line 1, in <module>
    stream = open("scores.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'scores.txt'

The final line names the problem: FileNotFoundError. No file called scores.txt exists in the working directory.

The line above the message shows line 1, where open failed. Nothing printed, because the program stopped before line 2.

Chapter 1 showed how to catch this failure with try and except FileNotFoundError. This chapter concentrates on the file operations themselves.

A script writes log.txt in a different folder from the script file. Is the file necessarily lost?

Goal. Decide whether a written file can end up in an unexpected folder.

Approach. Ask which folder the relative path is measured from.

Trace. A relative path starts from the working directory. That folder follows where the program was started, not where the script file sits.

Answer. Check the working directory and the path before writing another copy.

Result: The file is not necessarily lost. It is probably in the working directory.

Practise in one folder kept only for course files. A file operation can change real stored data, so choosing a mode is part of the program’s behaviour, not merely setup.

Common mistake: Do not assume a relative path is relative to the script file.

⚡ Quick Check Flashcards4 questions
Question 1
What survives a process restart: an ordinary local variable or a saved file?
Try answering before revealing!
Question 2
What identifies where a file should be opened?
Try answering before revealing!
Question 3
What is a file handle?
Try answering before revealing!
Question 4
A program opens "data.txt" with a relative path. Which folder does Python look in?
Try answering before revealing!

2.2. TYPES OF FILES

788 words · 4 min read

A text reader wants characters. Storage holds bytes. An encoding is the rule used to translate between these forms. Text mode performs that translation for you; binary mode gives you the bytes directly.

Consider a short note. A text read returns a Python string that you can compare with other strings. A binary read returns a bytes object. Neither view is automatically “more correct”; the required format decides which one is useful.

  1. Decide whether the program needs decoded text or raw bytes.
  2. For text, choose the encoding explicitly.
  3. For a binary format, use that format’s rules to interpret the returned bytes.
In simple words: The mode determines the kind of values you work with. The filename extension alone does not decode a format.

Two students open the same stored note. One sees readable text. The other sees b'read\n' and wonders what the b means. The stored bytes are identical; the two doors read them differently.

A text file stores characters as bytes, using an agreed rule called an encoding. The encoding maps each character to one or more bytes.

UTF-8 is the common choice, and the one this book always passes to open.

A text stream applies that rule for you. You hand it a string to write, and a read returns a string. Text mode can also translate newline conventions between systems.

A text file can hold prose, source code, JSON or a table stored as text. Those formats add rules of their own on top of the encoding.

A CSV file, for example, is plain text with one row per line and commas between fields. Section 2.7 builds one.

A binary file is read and written as bytes, with no decoding step. You work with bytes objects, written with a leading b, such as b"ABCDEFGH". Images, compressed archives and pickled objects are binary files.

Binary mode does not explain a format. The bytes still need that format’s own rules before they mean anything. Opening a picture as bytes shows large numbers, not the picture.

QuestionText streamBinary stream
What a read returnsA stringA bytes object
Who decodes the bytesThe stream, using an encodingNobody; you apply the format rules
Typical filesNotes, CSV, JSON, source codeImages, archives, pickled objects

Read the table. The middle row is the heart of the section. Text mode performs the byte-to-character conversion; binary mode hands you the raw bytes and stops there. The last row shows that the choice follows the format of the data, not personal taste.

Predict the output before running this complete example.

with open("note.txt", "w", encoding="utf-8") as stream:
    stream.write("read\n")
with open("note.txt", "rb") as stream:
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. The first with opens a text file for writing and encodes the string.
  2. Leaving that block closes the writer before the next open.
  3. The second open uses binary mode, so read returns bytes rather than a decoded string.

Output
b'read\n'

Read the same file in text mode and compare the type and printed representation.

The binary result includes a newline byte. In text mode, the corresponding read would return a string. Use the mode required by the format rather than choosing by the filename extension alone.

Try to predict the printed result first. The trace below explains every line.

with open("symbol.txt", "w", encoding="utf-8") as stream:
    stream.write("aθb")
with open("symbol.txt", "rb") as stream:
    data = stream.read()
print(len(data))
print(data)
with open("symbol.txt", encoding="utf-8") as stream:
    text = stream.read()
print(len(text))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 2 writes three characters: a, the Greek letter theta, and b.
  2. Line 3 reopens the file in binary mode, so read returns bytes.
  3. Line 5 prints 4. UTF-8 stores theta as two bytes; a and b need one byte each.
  4. Line 6 shows those four bytes. Theta appears as the two codes \xce and \xb8.
  5. Line 8 reads the same file in text mode. The stream decodes the bytes back into 3 characters.
  6. Line 9 prints 3. Four stored bytes became 3 characters.

Output
4
b'a\xce\xb8b'
3

Write the same text with encoding="ascii" instead. The write fails, because theta has no ASCII code. Explain the error in your own words.

The example shows the central lesson of this section. Characters and bytes are two views of the same stored data. The encoding decides how many bytes each character needs.

Common mistake: Binary mode does not mean “unreadable”; it means no automatic text decoding.

⚡ Quick Check Flashcards3 questions
Question 1
What kind of value does a binary read return?
Try answering before revealing!
Question 2
Why specify an encoding when writing text?
Try answering before revealing!
Question 3
The text "aθb" holds three characters. Why can the stored file hold four bytes?
Try answering before revealing!

2.3 OPENING AND CLOSING A TEXT FILE

946 words · 4 min read

Before opening a file, say what you intend: read existing content, replace it, add to it or create a new file only. Python’s mode argument expresses that choice. A wrong mode can change data before the main part of your program begins.

A with block makes the lifetime visible. Inside the block, use the open file. After the block, the file object is closed. The indentation helps you see exactly which statements still depend on it.

  1. Choose a mode from the intended effect, not from habit.
  2. Place the file operations inside with.
  3. Use the stored file again later by opening a new file object when needed.
In simple words: Closing ends access through one file object. It does not delete the stored file.

Student A wants to look at a scores file and opens it with mode w, believing that is the normal way to open anything. The scores vanish at once. A mode is permission, and w permits replacing the whole file.

A mode is a short code passed to open that states what you intend to do. Opening is an action, not a look. Each mode changes the stored file differently, and some change it before your first read or write.

ModePurposeImportant effect
rRead existing textFails if the file does not exist.
wWrite textCreates a file or truncates an existing file immediately on opening.
aAppend textCreates a missing file; writes go to the end.
xCreate text exclusivelyFails if the path already exists.
bBinary modifierUse rb or wb for bytes.
+Read/write modifierAdds reading and writing, as in r+; the base mode still matters.

Read the table row by row. Mode r is the polite guest: it reads and refuses a missing file instead of inventing one. Mode w truncates: opening with w empties an existing file at once. Mode a keeps earlier text and adds at the end. Mode x is the careful creator: it refuses a path that already exists. The b and + rows are modifiers, so they combine with a base letter such as r or w.

The close method ends access through one handle. The with statement closes the file for you: when the indented block ends, Python closes it, even if an error leaves the block early.

A helper that cleans up like this is called a context manager.

Manual closing needs care: pair open with close through try and finally, as chapter 1 showed. Forgetting close can leave written text unfinished. The next section explains why with a buffer.

Predict the output before running this complete example.

with open("session.txt", "w", encoding="utf-8") as stream:
    stream.write("ready")
print(stream.closed)

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Entering with opens the file and binds the file object to stream.
  2. The write runs while that object is open.
  3. The last print is after the with block. At that point, the context manager has closed the object.

Output
True

Inspect stream.closed inside the block as well as after it.

A closed stream cannot be used for further reads or writes. Open a new stream if a later step needs the file again. Closing a stream is different from deleting its file.

Before running the program, say the output in your own words.

with open("log.txt", "w", encoding="utf-8") as stream:
    stream.write("start\n")
with open("log.txt", "a", encoding="utf-8") as stream:
    stream.write("entry 2\n")
with open("log.txt", "a", encoding="utf-8") as stream:
    stream.write("entry 3\n")
with open("log.txt", encoding="utf-8") as stream:
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 1 uses w mode. The file is new here, so nothing old can be lost.
  2. Line 2 stores the first line and ends it with a newline character.
  3. Lines 3 and 4 open again with a mode. The existing text stays, and the new text goes after it.
  4. Lines 5 and 6 append one more line in the same way.
  5. Line 8 reads the whole file. The three lines appear in the order they were written.

Output
start
entry 2
entry 3

Change the mode in line 3 from "a" to "w" and predict what the final read prints before running.

Appending is the safe way to grow a log that is used over days or weeks. Every open with a adds at the end and never touches earlier lines. Growth is exactly what a log needs.

Mode x is the careful opposite of w: it creates a new file or refuses. The program below first creates log.txt and then asks x to create it again.

Python
with open("log.txt", "w", encoding="utf-8") as stream:
    stream.write("today\n")
with open("log.txt", "x", encoding="utf-8") as stream:
    stream.write("again\n")
Output
Traceback (most recent call last):
  File "newfile.py", line 3, in <module>
    with open("log.txt", "x") as stream:
         ~~~~^^^^^^^^^^^^^^^^
FileExistsError: [Errno 17] File exists: 'log.txt'

Lines 1 and 2 create log.txt and write one line. Line 3 then asks x to create the same path.

The creation is refused, because the path already exists. The final line names FileExistsError, and the marks under open show the failing call.

Closing a stream is not the end of the file. The stored bytes remain on the device until something deletes them. Reopen with a fresh open call whenever the program needs the data again.

Practise on files created only for this course. Keep one folder for practice files, so a wrong mode can never damage work you care about.
Common mistake: Opening with w can erase old content before the first write call.

⚡ Quick Check Flashcards4 questions
Question 1
Which mode avoids overwriting an existing file by failing instead?
Try answering before revealing!
Question 2
Does closing a file remove it?
Try answering before revealing!
Question 3
Why does mode a suit a log that grows over weeks?
Try answering before revealing!
Question 4
A task only needs to read a file. Which mode fits, and why?
Try answering before revealing!

2.4 WRITING TO A TEXT FILE

1,099 words · 5 min read

Writing text is like placing characters onto a long strip. A second write continues immediately after the first. Python does not guess whether you wanted a space, a comma or a new line between them.

Writelines is convenient when you already have several strings. Despite its name, it does not add a line ending to each string. The line endings must already be present in the values you supply.

  1. Choose the record format, including its separators.
  2. Build the strings with those separators included.
  3. Read the file back and inspect repr when spaces or newline characters are hard to see.
In simple words: The file contains what the writing code supplied, not what its visual layout in your source file seemed to suggest.

A beginner writes three words with three write calls and finds one long word in the file: penpencileraser. Nothing broke. write stored exactly what it was given, and the missing pieces were the separators.

The write method accepts one string in text mode and returns the number of characters written. It does not add a newline, a space or anything else.

The print statement adds a newline by default; write adds nothing you did not type.

Written text first rests in a buffer, a small holding area in memory. The stream sends buffered text to storage when the buffer fills, when you call flush, or when the file closes.

Close commits the buffer; a program that forgets it can leave text unfinished.

Text given to writeText waits in the bufferClose or flush commits itBytes rest in the file
The path one written string takes from a write call to the stored file.

Follow the diagram. The first box is your write call with its string. The second box is the buffer inside memory, where the text waits. The third box is the moment of commitment, reached by close or flush. The last box is storage, where the bytes finally rest. Reading the file before the third box can show an empty file, which the example below demonstrates.

Predict the output before running this complete example.

lines = ["focus\n", "break\n"]
with open("plan.txt", "w", encoding="utf-8") as stream:
    count = stream.write("start\n")
    stream.writelines(lines)
print(count)
with open("plan.txt", encoding="utf-8") as stream:
    print(repr(stream.read()))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. The first write stores one string and returns its character count.
  2. Writelines places the supplied strings immediately after it. Their existing newline characters create the line breaks.
  3. The reader reopens the completed file. Repr makes otherwise invisible newline characters visible in the output.

Output
6
'start\nfocus\nbreak\n'

Remove the newline from one supplied string and predict where the next word appears.

The count covers the first write only. It counts characters, which need not equal the number of encoded bytes for non-ASCII text. Writelines does not return a useful character count.

Write down what this program should print before you read the expected output.

stream = open("later.txt", "w", encoding="utf-8")
stream.write("hello\n")
reader = open("later.txt", encoding="utf-8")
print(repr(reader.read()))
stream.close()

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 1 opens the file without with. Closing is now the program’s own job.
  2. Line 2 hands the text to the stream. The text first rests in the buffer inside memory.
  3. The buffer has not been committed, so the stored file is still empty.
  4. Line 3 opens a reader on the same path. It sees the empty stored file.
  5. Line 4 prints an empty result: the reader finds no characters to read.
  6. Line 5 closes the writer at last. Only now does hello reach the file on storage.

Output
''

Move the close call above the reader open on line 3. Predict the printed result before running.

If a reader must see fresh text, close the writer first. Closing commits the buffer, and the reader then finds every character.

This program is why the with statement matters. It closes on every exit from the block, so a with block can never leave a file half-committed by accident.

The writelines method accepts an iterable of strings and writes them consecutively. It invents no separators, despite its name. Include newline characters yourself when each value belongs on a separate line.

Try to predict the printed result first. The trace below explains every line.

with open("results.csv", "w", encoding="utf-8") as stream:
    stream.write("Student A,80\n")
    stream.write("Student B,72\n")
with open("results.csv", encoding="utf-8") as stream:
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 2 writes the first row. The comma separates two fields, and the newline ends the row.
  2. Line 3 writes the second row directly after the first.
  3. Lines 4 and 5 read the file back. The rows print on separate lines because each row stored its own newline.

Output
Student A,80
Student B,72

Add a third row "Student C,91\n" with another write call, then predict the printed output.

The example builds a CSV file by hand. write adds only the characters you give it. The row shape exists because the writer supplied both the comma and the newline.

Before running the program, say the output in your own words.

items = ["pen", "pencil", "eraser"]
with open("list.txt", "w", encoding="utf-8") as stream:
    stream.writelines(items)
with open("list.txt", encoding="utf-8") as stream:
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 1 collects three words. None of them holds a newline character.
  2. Line 3 passes the list to writelines. The method writes the values one after another.
  3. No separator appears between the values, because writelines never adds one.
  4. Line 5 reads the file back. The three words print joined into one line.

Output
penpencileraser

Change the list to ["pen\n", "pencil\n", "eraser\n"] and predict the printed output before running.

A program calls writelines with three plain words and the file becomes one glued line. What is the smallest repair?

Goal. Restore one stored line per word without changing the reading code.

Approach. Ask what separates two stored lines, and check whether the values carry it.

Trace. Lines end with newline characters. The values hold none, and writelines refuses to invent them. The file therefore holds one line of 15 characters.

Answer. Give every value its own newline, or write the values one at a time with value + "\n".

Result: Separators must be part of the supplied text; writelines adds none.

Common mistake: Do not expect writelines to insert line breaks between its elements.

⚡ Quick Check Flashcards4 questions
Question 1
How would you put “done” on its own line?
Try answering before revealing!
Question 2
Does write add a space between two calls?
Try answering before revealing!
Question 3
What is a buffer?
Try answering before revealing!
Question 4
What does the number returned by write count?
Try answering before revealing!

2.5 READING FROM A TEXT FILE

960 words · 4 min read

A file object remembers where its next read will begin. After reading a line, the next read normally starts after that line. Earlier characters remain stored in the file; the reader has simply moved past them.

Think of moving a bookmark while reading. Readline advances to the next line. Read without a size consumes the remaining text. Reaching the end gives an empty result for an ordinary read, not a fresh copy of the beginning.

  1. Identify the reader’s current position.
  2. Choose whether you want a line, a bounded amount or everything remaining.
  3. Interpret an empty result according to the method, and distinguish it from a line that contains a newline.
In simple words: If you want to read again from the beginning, explicitly reposition or reopen the file.

Student A calls read() on a fresh file, prints the text, then calls read() again and prints nothing. The file did not vanish. The reader reached the end and stayed there.

A stream keeps a position, the place where the next read starts. Reading moves the position forward; it never deletes stored text.

When the position reaches the end, read returns the empty string "". ==An empty string from a read is the end-of-file signal.

==

MethodResultTypical use
read()A string containing the remaining textSmall complete files.
read(n)Up to n characters in text modeBounded reads.
readline()The next line, usually including its newlineLine-by-line control.
readlines()A list of the remaining linesSmall files needing a list.
for line in streamSuccessive linesStreaming traversal without loading everything.

How to read this table. The five rows answer five different questions: everything left, a bounded amount, one line, all lines at once, or line after line without storing them. Beginners usually need readline or the loop. readlines is comfortable for small files and wasteful for large ones.

Predict the output before running this complete example.

with open("steps.txt", "w", encoding="utf-8") as stream:
    stream.write("open\ncheck\n")
with open("steps.txt", encoding="utf-8") as stream:
    print(repr(stream.readline()))
    print(repr(stream.read()))
    print(repr(stream.read()))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. The writer creates a small file with separate lines.
  2. Readline consumes the first line and advances the reading position.
  3. Read then consumes only what remains. The last read has nothing left and returns an empty string.

Output
'open\n'
'check\n'
''

Add another readline before read and predict what remains for read.

Reading advances the stream position. The next read starts there, not at the beginning.

An empty string from a positive-sized or unbounded text read indicates end of file. A blank line is different: readline normally returns a string containing its newline.

Write down what this program should print before you read the expected output.

with open("steps.txt", "w", encoding="utf-8") as stream:
    stream.write("open\ncheck\ndone\n")
with open("steps.txt", encoding="utf-8") as stream:
    lines = stream.readlines()
print(len(lines))
print(lines[1])

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 2 stores three lines, each ending with its own newline character.
  2. Line 4 calls readlines. The method returns a list of the remaining lines, in order.
  3. Line 5 prints 2, the number of items in the list.
  4. Line 6 prints the second item. It is the text check together with its stored newline.

Output
3
check

Print lines[0] instead and predict the printed word before running.

Each list item keeps its newline character. print adds a second one, so a terminal shows a blank line after check. The stored file has no blank line; the doubling happens on the screen.

Try to predict the printed result first. The trace below explains every line.

with open("plan.txt", "w", encoding="utf-8") as stream:
    stream.write("read\nrest\nreview\n")
count = 0
with open("plan.txt", encoding="utf-8") as stream:
    for line in stream:
        count += 1
print(count)

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 2 stores three lines. Each one ends with its own newline character.
  2. Line 3 starts the counter at zero.
  3. Lines 5 and 6 walk through the file one line at a time. The loop adds 1 for each line.
  4. The for loop reads the stream directly, so no list of lines is ever built.
  5. Line 7 prints 2.

Output
3

Remove the final "\n" from line 2 and predict the count before running. The loop still counts the last line, even without its newline.

Before running the program, say the output in your own words.

with open("notes.txt", "w", encoding="utf-8") as stream:
    stream.write("first\n\nlast\n")
with open("notes.txt", encoding="utf-8") as stream:
    print(repr(stream.readline()))
    print(repr(stream.readline()))
    print(repr(stream.readline()))
    print(repr(stream.readline()))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 2 stores three lines. The middle line is empty except for its newline character.
  2. Line 4 reads the first line. Repr shows it as 'first\n'.
  3. Line 5 reads the blank line. It is the single character \n, not an empty result.
  4. Line 6 reads the last line, 'last\n'.
  5. Line 7 reads again. Nothing remains, so readline returns the empty string.

Output
'first\n'
'\n'
'last\n'
''

Change line 2 to "first\nlast\n" and predict the four printed lines before running.

The example settles a question that confuses many beginners. ==A blank line is real data, not the end.

The end-of-file signal is the empty string alone. Test line "" for the end of a line-based read, and line.strip() == "" for a line holding nothing but spaces.

Using strip removes whitespace from both ends. That is useful for some records, but it can erase meaningful spaces. Use rstrip("\n") when only the final newline should be removed.

When output looks wrong, print repr(line) first. The invisible newline and space characters become visible.
Common mistake: Repeated reads do not automatically restart from the beginning.

⚡ Quick Check Flashcards4 questions
Question 1
What distinguishes a blank line from end of file in readline?
Try answering before revealing!
Question 2
Which approach is usually better for a very large line-based file?
Try answering before revealing!
Question 3
Which reading method builds a list of all lines at once?
Try answering before revealing!
Question 4
After read() returns "", did the file lose its contents?
Try answering before revealing!

2.6 SETTING OFFSETS IN A FILE

731 words · 3 min read

Tell asks where the file object is positioned. Seek moves that position. Neither operation says that the content has been edited. A later read starts from the new position.

Binary positions count bytes. Text positions are more complicated because decoding and newline handling can be involved. For text, store a position returned by tell and restore that position rather than inventing offsets by counting visible letters.

  1. Ask whether the stream is binary or text.
  2. Use a positioning operation supported for that kind of stream.
  3. Predict the next value to be read, then read it to test your understanding.
In simple words: Positioning and editing are different actions. A successful seek does not mean bytes were inserted or removed.

A music player can start in the middle of a track without playing the first half. File streams can jump too, but only when the program steers the position on purpose.

An offset is a counted distance from the beginning of the file. ==Offsets count from zero.

== The first byte sits at offset 0, the second at offset 1, and so on. A text stream and a binary stream obey different rules about positions.

In a binary stream, tell reports a byte offset from the beginning. In a text stream, its value is an opaque position token: do not assume it is a simple character count.

The seek method moves the position of a stream. A second argument, called whence, says what the offset is measured from.

Binary streams support all three reference points; ordinary text streams support the safe patterns of returning to the beginning and restoring a value obtained from tell.

Whence valueCounts from
0The start of the file
1The current position
2The end of the file

Work down the rows. Whence 0 is the default and the easiest to reason about: the offset is a distance from the beginning. Whence 1 and 2 measure from the current position or the end, and negative offsets then move backwards. The kept example below uses whence 2 to reach the final bytes.

Predict the output before running this complete example.

with open("bytes.bin", "wb") as stream:
    stream.write(b"ABCDEFGH")
with open("bytes.bin", "rb") as stream:
    stream.seek(3)
    print(stream.tell())
    print(stream.read(2))
    stream.seek(-2, 2)
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. The writer stores a known sequence of bytes.
  2. Seek moves the next-read position; it does not insert or remove data.
  3. The short read consumes bytes from that position.
  4. The later seek uses the end as its reference point and the final read consumes the remaining suffix.

Output
3
b'DE'
b'GH'

Return to the beginning with seek(0), then read the whole file.

The offset is zero-based. Positioning at the fourth byte means skipping the preceding bytes. Seeking does not change those bytes; a later write may change content depending on the mode.

Write down what this program should print before you read the expected output.

with open("letters.bin", "wb") as stream:
    stream.write(b"STUVWXYZ")
with open("letters.bin", "rb") as stream:
    print(stream.read(4))
    stream.seek(0)
    print(stream.read(4))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 2 stores eight bytes.
  2. Line 4 reads four bytes from the start. The position now stands after the fourth byte.
  3. Line 5 moves the position back to offset 0 inside the same stream.
  4. Line 6 reads four bytes again. The same four bytes appear a second time.

Output
b'STUV'
b'STUV'

Change line 5 to stream.seek(2) and predict the second printed value before running.

Seeking changes position only. It inserts nothing and removes nothing, and the stored bytes are exactly as they were.

In a read mode such as rb nothing can change at all; in a mode that permits writing, a later write overwrites bytes from the current position onwards.

For text streams, remember the two safe patterns. Use seek(0) to return to the beginning.

Store a value that tell returned, and restore exactly that value later. Never do arithmetic on a text tell token, because decoding and newline translation make the numbers meaningless.

After any seek, a print(stream.tell()) confirms where the stream stands before you read.
Common mistake: Do not use arbitrary byte arithmetic on a text-stream tell token.

⚡ Quick Check Flashcards4 questions
Question 1
Does seek itself delete bytes?
Try answering before revealing!
Question 2
How can you return safely to the beginning of a text stream?
Try answering before revealing!
Question 3
In b"ABCDEFGH", which byte sits at offset 0?
Try answering before revealing!
Question 4
Which whence value measures from the end of the file?
Try answering before revealing!

2.7 CREATING AND TRAVERSING A TEXT FILE

1,183 words · 5 min read

A small data file needs an agreed shape. If one record occupies one line, the writer must create that line and the reader must interpret it. Saving numbers as text does not remove the need to convert them back into numeric values.

Follow one record from start to finish: a value becomes text, the text is stored, a later run reads that text, and parsing recovers the value. This journey makes it easier to find where an incorrect value first appeared.

  1. Describe one record and its separators.
  2. Write a small known collection, then close the writer.
  3. Read the collection back, validate each record, and compare the recovered result with the original.
In simple words: Validate before combining records. Otherwise one malformed line can silently distort the final total.

The study timer from section 2.1 now keeps real records: one line per study session. One small program writes the file, and a second part reads it and adds the values up.

This section builds both, then extends the format to marks.

In this example each line stores the minutes spent in one study session. A record is one stored item, so one line is one record.

A field is one value inside a record; the marks file later in this section stores two fields per line, separated by a comma.

Predict the output before running this complete example.

sessions = [14, 22, 18]
with open("minutes.txt", "w", encoding="utf-8") as stream:
    for minutes in sessions:
        stream.write(str(minutes) + "\n")
total = 0
with open("minutes.txt", encoding="utf-8") as stream:
    for line in stream:
        total += int(line)
print(total)

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. The writing loop turns each number into text and supplies its line break.
  2. The file is closed, then reopened for reading from the beginning.
  3. The reading loop turns each line back into an integer before adding it to total.

Output
54

Add another session value and predict the new total before running.

The writing loop turns each number into text and stores it on its own line. The three sessions hold 54 minutes in total, and the reading loop recovers exactly what the writing loop stored, because both sides follow the same line format.

A record with several fields needs a way to take one line apart. The string method split cuts a line at a chosen character and returns the pieces as a list.

Try to predict the printed result first. The trace below explains every line.

line = "Student A,80\n"
fields = line.strip().split(",")
print(fields)
print(fields[0], fields[1])

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 is one stored row, exactly as a reader receives it, newline included.
  2. Line 2 removes the newline with strip, then cuts the text at the comma. Split returns a list of two strings.
  3. Line 3 shows that list. Both fields are text, even the mark.
  4. Line 4 prints the two fields with a space between them.

Output
['Student A', '80']
Student A 80

Change line 2 to split on a space instead and predict the new list before running. The mark arrives glued to the letter A as "A,80".

Split always returns strings. A field read from a text file is text until you convert it. The two characters in "80" become the number 80 only after int() is applied.

The next program joins the skills of the whole chapter. It stores three students, reads the file back line by line, splits each line, converts the marks and prints the total and the class average.

Before running the program, say the output in your own words.

rows = ["Student A,80\n", "Student B,72\n", "Student C,91\n"]
with open("marks.csv", "w", encoding="utf-8") as stream:
    stream.writelines(rows)
total = 0
count = 0
with open("marks.csv", encoding="utf-8") as stream:
    for line in stream:
        fields = line.strip().split(",")
        mark = int(fields[1])
        total += mark
        count += 1
print(total, count)
print(total / count)

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 1 lists 3 rows. Each row ends with a newline character.
  2. Line 3 writes all rows in one call, and the with block closes the writer afterwards.
  3. Lines 4 and 5 prepare two counters before reading.
  4. Lines 7 to 11 form the reading loop. Each pass handles one stored row.
  5. Line 8 cleans the row and cuts it at the comma.
  6. Line 9 converts the second field into the number 80, 72 or 91.
  7. Lines 10 and 11 add the mark to the total and count the row.
  8. Line 12 prints the total 243 and the row count 3. Line 13 prints the class average as 81.0.

Output
243 3
81.0

Add the row "Student D,64\n" to line 1 and predict both printed lines before running.

Build each record lineWrite all recordsClose the writerReopen for readingRead and parse each line
One record travels from a value in memory to a parsed field in the reading loop.

How to read the diagram. The boxes follow one record from left to right through the whole journey. The first box builds the line: value turned to text, separator added, newline added. The second and third boxes store the lines and commit them. The fourth box reopens the file for reading. The last box is the parsing loop, where strip, split and int recover the original value. A mistake can hide in any box, so this picture is also a checklist when a total comes out wrong.

A writer stored mark rows without newline characters, so the file holds Student A,80Student B,72. The reading loop still calls int(fields[1]) on every line. What happens?

Goal. Predict the failure before running the reading loop.

Approach. Follow one line through strip, split and int with the glued text in hand.

Trace. The row strips to Student A,80Student B,72. Splitting at commas gives the fields Student A, 80Student B and 72. The first int call receives 80Student B, which is not a number.

Answer. The loop raises ValueError with the message invalid literal for int(). The missing newline corrupted the second field.

Result: The stored separators decide the parse. A writer mistake appears as a reader error, so check the file with repr when parsing fails.

Traversal means visiting records in order. A robust reader also decides what a blank or malformed line means.

It might reject the whole file, report a line number, or skip a record with a clear warning. Quietly converting every bad record to zero can hide missing data.

Practise destructive modes on a copy of the file. One open call with the wrong mode can change the original for good.

When updating a valuable file, a safer design often writes a new temporary file and replaces the old file only after success. This is a design extension, not an effect that w mode provides automatically.

Common mistake: Reading a numeric-looking string does not automatically make it a number.

⚡ Quick Check Flashcards4 questions
Question 1
Why is int used in the reading loop?
Try answering before revealing!
Question 2
What policy should be defined before skipping invalid records?
Try answering before revealing!
Question 3
What does "Student A,80".split(",") return?
Try answering before revealing!
Question 4
Why strip a line before splitting it?
Try answering before revealing!

2.8 THE PICKLE MODULE

780 words · 4 min read

A Python dictionary can contain lists and other structured values. Its printed form is convenient for inspection, but a storage format needs a reliable reconstruction rule. Pickle supplies such a rule for supported Python objects.

Dump serialises the object into a binary form. Load reconstructs an object from that form. The reconstructed object can have the same values and structure without being the very same object in memory.

  1. Create a record in the program.
  2. Dump it through a binary writer, then reopen the saved file.
  3. Load the record and compare its structure and values with the original.
In simple words: Only load a trusted pickle. Reconstruction can perform code-related actions, so a pickle is not a harmless text note.

A dictionary holds a tag and a list of minutes. Printing it looks ready to save. Printed text is only a picture of the object, though. What a later program needs is the object itself, with its structure intact.

Serialisation writes an object as a sequence of bytes. The pickle module does this for supported Python objects. dump writes an object to a binary stream, and load rebuilds the next object from that stream.

Pickle therefore needs binary modes: wb to save and rb to load.

The rebuilt object equals the original, but it is a new object in memory. Equality compares values and structure, not identity.

Any later program that loads the file also needs a compatible Python environment and any required class definitions.

Predict the output before running this complete example.

import pickle
record = {"tag": "practice", "minutes": [12, 18]}
with open("record.bin", "wb") as stream:
    pickle.dump(record, stream)
with open("record.bin", "rb") as stream:
    restored = pickle.load(stream)
print(restored == record)
print(sum(restored["minutes"]))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Dump writes the complete record structure into a binary file.
  2. Load reconstructs the next saved object from the reopened binary stream.
  3. The equality check compares the restored structure with the original. The final sum uses the restored list.

Output
True
30

Add a duration to the saved list and confirm that it also appears in the restored record.

You can dump several objects sequentially and load them in the same order. Reading beyond the saved objects raises EOFError.

A clear format, such as one saved collection, is often easier to maintain than guessing how many objects follow.

Build a Python objectDump writes binary bytesClose the binary writerLoad rebuilds the objectCompare with the original
One saved object travels from memory through a pickle file and back.

Read the diagram. The first box is the object in memory, with its structure. The second box serialises it into binary bytes through dump. The third box closes the writer so every byte is committed. The fourth box rebuilds an equal object through load. The last box compares the two and confirms the round trip. If the comparison fails, one of the five boxes is the place to look.

Write down what this program should print before you read the expected output.

import pickle
with open("two.bin", "wb") as stream:
    pickle.dump(["a", "b"], stream)
    pickle.dump([10, 20, 30], stream)
with open("two.bin", "rb") as stream:
    print(pickle.load(stream))
    print(pickle.load(stream))
    try:
        pickle.load(stream)
    except EOFError:
        print("No more saved objects")

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 1 imports the pickle module.
  2. Lines 3 and 4 save two lists, one after the other, into the same binary file.
  3. Line 6 loads the first saved object, and line 7 loads the second. The order is preserved.
  4. Line 9 tries to load a third object. None was saved, so the stream has nothing left.
  5. Pickle raises EOFError at that point. Lines 10 and 11 catch it and print a clear message.

Output
['a', 'b']
[10, 20, 30]
No more saved objects

Add pickle.dump([4], stream) as a new line inside the first with block, then predict the three printed values.

Only unpickle data you trust. Loading a malicious pickle can execute code.

A file extension, an email sender name or a promise that a file contains “only data” does not establish trust. ==Load a pickle only from a source you trust.

== JSON is often more suitable when interoperating with other languages, although its validation still matters.

Compared with a text file, pickle keeps list and dictionary structure without any splitting or converting. The price is that the file is Python-specific and unreadable in a text editor.

A CSV file can be opened anywhere but stores only text that your code must parse.

Common mistake: Do not load an untrusted downloaded pickle as if it were harmless plain text.

⚡ Quick Check Flashcards3 questions
Question 1
Which modes belong with pickle dump and load?
Try answering before revealing!
Question 2
Does successful unpickling prove the values satisfy your application rules?
Try answering before revealing!
Question 3
Which exception announces that no further objects remain in a pickle file?
Try answering before revealing!

Summary

230 words · 1 min read

Use these points to test what you can explain without looking back.

  • A variable forgets when the program ends; a file keeps its bytes on a storage device.
  • A path locates a file. A relative path is measured from the working directory; an absolute path starts from the filesystem root.
  • A stream is the active interface used to access a file. Opening creates it, reading and writing use it, closing releases it.
  • Text streams decode bytes using an encoding. Binary streams expose bytes directly.
  • Choose modes carefully: w truncates, a appends, and x requires a new path.
  • Use with for ordinary file lifetime management; it closes on every exit from the block.
  • write and writelines store exactly the text given, including any newline characters you supply.
  • Written text waits in a buffer until flush or close commits it.
  • Reading advances the position. read, readline, readlines and a for loop answer different needs.
  • A blank line reads as "\n"; the empty string signals end of file.
  • tell and seek steer the position. Binary offsets count bytes from zero; text positions are opaque tokens.
  • Define a record format, split lines into fields, and convert text values before arithmetic.
  • Pickle preserves supported Python structure but must only be loaded from trusted sources.
For each algorithm or rule, give an input for which it works and a condition under which it needs extra care.

Exercise

1,419 words · 6 min read

Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.

2.1 A teammate opens an existing log file with mode w to inspect its contents. What happens to the log, and which two modes would have been safe?

2.2 Predict the full output of this program, then explain each printed line.

Try to predict the printed result first. The trace below explains every line.

with open("notes.txt", "w", encoding="utf-8") as stream:
    stream.write("go\n")
with open("notes.txt", "a", encoding="utf-8") as stream:
    stream.write("stop\n")
with open("notes.txt", encoding="utf-8") as stream:
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 2 stores go with its newline in a new file.
  2. Lines 3 and 4 open in append mode, so stop lands after go.
  3. Line 6 reads the whole file and prints both lines in order.

Output
go
stop

Change line 3 to mode "w" and predict what the final read prints before running.

2.3 This program should print a settings file. Instead it destroys the settings. Name the wrong character, state the second problem, and give the safe repair.

Python
with open("settings.txt", "w", encoding="utf-8") as stream:
    print(stream.read())

2.4 Predict every printed line, including any blank lines.

Before running the program, say the output in your own words.

with open("pair.txt", "w", encoding="utf-8") as stream:
    stream.write("one\ntwo\n")
with open("pair.txt", encoding="utf-8") as stream:
    print(stream.readline())
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 4 reads the first line, one together with its stored newline.
  2. print adds a second newline, so a blank line appears after one on the screen.
  3. Line 5 reads the rest of the file and prints two the same way.

Output
one

two

Rewrite the two prints as print(stream.readline(), end="") and print(stream.read(), end="") and predict the new output.

2.5 A file holds the text "1\n2\n3\n". A program calls readline() three times and then calls read() once more. What does that final read return, and why?

2.6 Predict both printed lines.

Write down what this program should print before you read the expected output.

with open("colors.txt", "w", encoding="utf-8") as stream:
    stream.write("red\nblue\n")
with open("colors.txt", encoding="utf-8") as stream:
    lines = stream.readlines()
print(len(lines))
print(lines[0])

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 4 builds a list of the remaining lines, so the list holds 2 items.
  2. Line 5 prints 2.
  3. Line 6 prints the first item: the text red together with its stored newline.

Output
2
red

Predict print(lines[1]) for the same file before running it.

2.7 A program writes important results and then ends without closing the stream or using with. Name the holding area that delays the text, and state the two calls that commit it.

2.8 Write a function save_sessions(path, sessions) that stores one session value per line, then store the values 12, 15 and 9 and print the file to check.

2.9 Predict all three printed lines.

Before running the program, say the output in your own words.

with open("demo.bin", "wb") as stream:
    stream.write(b"ABCDEF")
with open("demo.bin", "rb") as stream:
    stream.seek(2)
    print(stream.tell())
    print(stream.read(2))
    stream.seek(1)
    print(stream.read(1))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 4 moves the position to offset 2, and line 5 confirms it.
  2. Line 6 reads the bytes at offsets 2 and 3.
  3. Line 7 moves back to offset 1, and line 8 reads the single byte there.

Output
2
b'CD'
b'B'

Predict the printed values if line 7 used stream.seek(-1, 2) instead.

2.10 Why is a tell value from a text stream unsafe to treat as a byte count?

2.11 Write a short program that prints a text file twice without opening it a second time.

2.12 A marks file was written with spaces instead of commas, so one row reads "Student A 80". The reader calls line.strip().split(",") and then fields[1]. What goes wrong, and what are the two repairs?

2.13 Predict both printed lines.

Try to predict the printed result first. The trace below explains every line.

rows = ["Student A,70\n", "Student B,90\n"]
with open("marks.csv", "w", encoding="utf-8") as stream:
    stream.writelines(rows)
total = 0
count = 0
with open("marks.csv", encoding="utf-8") as stream:
    for line in stream:
        fields = line.strip().split(",")
        total += int(fields[1])
        count += 1
print(total)
print(total / count)

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 3 stores both rows, and the with block closes the writer.
  2. The loop splits each cleaned line at the comma and converts the mark field.
  3. Line 11 prints the total 160.
  4. Line 12 prints the average of the two marks as 80.0.

Output
160
80.0

Add the row "Student C,84\n" and predict both printed lines before running.

2.14 A marks file begins with a header row "Student,Mark". The reading loop calls int(fields[1]) on every line. What happens on the header line, and give one repair.

2.15 Predict both printed lines.

Before running the program, say the output in your own words.

import pickle
saved = {"level": 3, "minutes": [10, 20, 40]}
with open("game.bin", "wb") as stream:
    pickle.dump(saved, stream)
with open("game.bin", "rb") as stream:
    restored = pickle.load(stream)
print(restored == saved)
print(sum(restored["minutes"]))

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 4 serialises the whole dictionary, including the nested list, into binary bytes.
  2. Line 6 rebuilds an equal object from the reopened stream.
  3. Line 7 compares the restored structure with the original and prints True.
  4. Line 8 sums the restored list and prints 70.

Output
True
70

Change the saved list to [10, 20] and predict both printed lines before running.

2.16 Give one reason to store marks in a CSV file rather than a pickle, and one reason to prefer pickle.

Answers

2.1 Opening with w empties the file at once, before anything is read, and a write-only stream cannot read anyway. Mode r would have read it safely; mode a would have been safe for adding lines.

2.2 go, then stop. The first write stores go with its newline; the append adds stop after it, so the reader sees both lines in order.

2.3 The wrong character is w in the mode. It truncates the file before line 2 runs.

The second problem is that a write-only stream cannot read, so the read call fails as well. The repair is mode "r", which reads without changing anything.

2.4 one, then a blank line, then two. Each returned string already ends with a newline, and print adds another one.

2.5 The empty string. The first three reads consumed all three lines, so the position stands at the end of the file, which is the end-of-file signal.

2.6 2, then red. readlines returns one list item per stored line, and every item keeps its own newline character.

2.7 The buffer holds written text in memory. flush commits it early, and close commits whatever remains. The with statement closes for you on every exit from its block.

2.8 The function loops over the values, converts each one with str, and appends "\n". The stored file then prints as 12, 15 and 9 on separate lines.

Try to predict the printed result first. The trace below explains every line.

def save_sessions(path, sessions):
    with open(path, "w", encoding="utf-8") as stream:
        for minutes in sessions:
            stream.write(str(minutes) + "\n")

save_sessions("runs.txt", [12, 15, 9])
with open("runs.txt", encoding="utf-8") as stream:
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 1 defines the function. Nothing runs yet.
  2. Lines 2 to 4 hold the with block. Each session value becomes text with its own newline.
  3. Line 6 calls the function. The file runs.txt is created and filled with 3 lines.
  4. Lines 7 and 8 reopen for reading and print the stored text.

Output
12
15
9

Call the function a second time with mode a and predict the printed file.

2.9 2, then b'CD', then b'B'. Offsets count from zero, so offset 2 is the third byte.

2.10 A text stream token describes a decoding position, not a plain byte offset, because encoding and newline translation are involved. Treat it as opaque: store it and restore it, but never do arithmetic on it.

2.11 Read once, call seek(0) on the same stream, then read again. The text prints as roses, a blank line, then roses: each returned string ends with a newline and print adds another.

Write down what this program should print before you read the expected output.

with open("poem.txt", "w", encoding="utf-8") as stream:
    stream.write("roses\n")
with open("poem.txt", encoding="utf-8") as stream:
    print(stream.read())
    stream.seek(0)
    print(stream.read())

Copy the code, open the playground, and paste it into the console. Files are temporary browser files.

  1. Line 4 reads and prints the whole file. The returned text ends with a newline, and print adds another one, so a blank line appears.
  2. Line 5 returns to offset 0 inside the same open stream.
  3. Line 6 reads the same text again, without opening the file a second time.

Output
roses

roses

Replace line 5 with stream.seek(3) and predict what the second print shows.

2.12 Splitting at a comma returns one field, so fields[1] raises IndexError. The writer must store a comma separator, or the reader must split at the character the writer actually used.

Agree on the format before either program is written.

2.13 160 and then 80.0. The loop adds 70 and 90 into the total and divides by the row count of 2 for the average.

2.14 int receives the text Mark, so the loop raises ValueError with an invalid-literal message. Skip the first line before the loop with next(stream), or store the file without a header and describe the columns beside the code.

2.15 True, then 70. The restored dictionary equals the original, and its minutes list sums to 70.

2.16 CSV is plain text: any editor can show it and other languages can read it, with no trust concerns. Pickle keeps list and dictionary structure directly, so the loading code needs no splitting or converting.

Up next
Continue to the next chapter