Variables vanish when a program ends. To keep data, a program writes it to a file on disk and reads it back later.

Types of Files

A text file stores characters that people can read, such as a .txt or .py file, and is made of lines ending with a newline. A binary file stores bytes exactly as they are held in memory, such as an image or an audio file, and is not readable as text. Text files are easy to edit, while binary files are more compact.

Opening and Closing Files

A file is opened with open(name, mode). The modes are "r" for reading, "w" for writing which erases old content, "a" for appending at the end, and "r+" for reading and writing. Adding "b", as in "rb" or "wb", selects binary mode. The call returns a file object. The safe way to use it is the with statement, which closes the file automatically, even if an error occurs.

Definition: File mode. A letter given to open() that states how a file is used, such as r for read, w for write and a for append, with b added for binary files.

Reading and Writing Text

The method write(s) writes a string and does not add a newline by itself. read() returns the whole content as one string, readline() returns the next line, and readlines() returns a list of all lines. A for loop over the file object reads one line at a time, which is the best choice for large files. The method seek(0) returns to the start of the file, and tell() gives the current position.

Binary Files

In binary mode, data must be written as bytes. A string is converted with encode(), and bytes are read back and converted with decode(). Binary files are read with read(n) for n bytes. The pickle module, in the next topic, is the usual way to store Python objects in binary form.

Table 3.4: File modes

Mode Meaning If file is missing
r Read Error
w Write, erase old content Created
a Append at end Created
rb, wb Binary read, write As above

Example 3.4: Copying alternate lines

Problem: Write a program that creates a file with five lines, then copies the odd-numbered lines (1, 3, 5) into a second file.

Solution:

  1. Write the lines with a with block.
  2. Read file1 line by line using enumerate, starting from 1.
  3. Write a line to file2 when its number is odd.

Result: file2 contains lines 1, 3 and 5 of file1.

with open("file1.txt", "w") as f:
    for i in range(1, 6):
        f.write("line " + str(i) + "\n")
with open("file1.txt") as f, open("file2.txt", "w") as g:
    for n, line in enumerate(f, 1):
        if n % 2 == 1:
            g.write(line)
with open("file2.txt") as g:
    print(g.read().split("\n"))
with open("data.bin", "wb") as b:
    b.write("Hi".encode())
with open("data.bin", "rb") as b:
    print(b.read())

Output

['line 1', 'line 3', 'line 5', '']
b'Hi'

Common mistakes

  • Opening a file with "w" when the old content must be kept. Use "a" instead.
  • Forgetting to close a file, which can lose data. Use the with statement.
  • Forgetting that write() does not add a newline.

Key takeaways

  • open(name, mode) opens a file, and with closes it automatically.
  • r reads, w writes and erases, a appends.
  • read(), readline() and readlines() read text.
  • A b in the mode selects binary files.

Practice questions

  1. What is the difference between modes w and a?
  2. Why is the with statement used for files?
  3. What does readlines() return?

Answers to the practice questions

  1. w erases existing content, a adds to the end.
  2. It closes the file automatically.
  3. A list of all lines of the file.

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit III