Beginner   Chapter 103 · 25 min read · Module 8: File Handling

Working with Text Files

Learning objectives
  • After this chapter you can read a whole text file with read() and line by line with a for loop.
  • You can use readline() and readlines() and tell how they differ.
  • You can write text with write() and writelines() and add newlines correctly.
  • You can set encoding="utf-8" so text with special characters is saved and loaded safely.
  • You can process a text file to count lines and words.

Text files are the simplest and most common kind of file. Notes, logs, source code, and configuration files are all plain text. Python makes it easy to read them and to create them.

A text file is made of characters and lines. Each line ends with a newline character, which Python shows as \n. Many beginner problems come from forgetting that this newline is part of the line you read, or that write() does not add one for you.

In this chapter you will read files in several ways, write files, handle special characters with the right encoding, and finish with a small word counter. Every example uses the with statement from the previous chapter.

Reading the whole file

The method read() returns the entire content of the file as one string. It is the easiest choice for small files. For a very large file it uses a lot of memory, because everything is loaded at once. You can also pass a number, such as read(5), to get only that many characters.

Example 1: read() and read(n)
with open("poem.txt", "w", encoding="utf-8") as f:
    f.write("Roses are red\nViolets are blue\n")

with open("poem.txt", encoding="utf-8") as f:
    print(f.read(5))
    rest = f.read()

print(repr(rest))
Roses ' are red\nViolets are blue\n'

After read(5) the file position moves forward by five characters, so the next read() continues from there. The repr() function shows the hidden \n characters, which is very useful when you debug.

Reading line by line

The best way to process a file is to loop over the file object. Python gives you one line at a time and never loads the whole file. Each line still carries its newline at the end, so use strip() or rstrip("\n") when you do not want it.

Example 2: Loop over lines
with open("cities.txt", "w", encoding="utf-8") as f:
    f.write("Delhi\nMumbai\nPune\n")

with open("cities.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())
1 Delhi 2 Mumbai 3 Pune

There are two other reading methods. readline() returns the next single line, and returns an empty string "" when the file is finished. readlines() returns a list of all the lines. Use the loop for big files, and readlines() when you really want a list.

MethodReturnsGood for
read()one string with everythingsmall files
read(n)up to n charactersreading in pieces
readline()the next line as a stringstep by step reading
readlines()a list of all linessmall files when you need a list
for line in fone line each timeany size of file
Example 3: readline and readlines
with open("cities.txt", "w", encoding="utf-8") as f:
    f.write("Delhi\nMumbai\nPune\n")

with open("cities.txt", encoding="utf-8") as f:
    first = f.readline()
    others = f.readlines()

print(repr(first))
print(others)
'Delhi\n' ['Mumbai\n', 'Pune\n']

Writing text

The method write() takes one string and writes it. It returns the number of characters written, and it does not add a newline, so you must add \n yourself. The method writelines() takes a list (or any iterable) of strings, and it also does not add newlines.

Example 4: write and writelines
names = ["Asha", "Ravi", "Meena"]
with open("names.txt", "w", encoding="utf-8") as f:
    count = f.write("Names:\n")
    f.writelines(name + "\n" for name in names)

print(count)
with open("names.txt", encoding="utf-8") as f:
    print(f.read(), end="")
7 Names: Asha Ravi Meena

Remember that mode "w" erases the old content. Use "a" when you want to add lines at the end of an existing file.

Encoding and special characters

A computer stores characters as bytes, and the encoding is the rule that connects the two. The most common and safest choice is UTF-8, which can store letters of all languages and symbols. If you do not give an encoding, Python picks a default that depends on the operating system, so the same program can behave differently on two computers. For this reason, always write encoding="utf-8" when you open a text file.

A small word counter

Let us put the pieces together. The program below creates a file, then reads it once and counts lines and words. The split() method breaks a line at spaces, so the length of the result is the number of words in that line.

Example 5: Count lines and words
text = "Python is fun\nFiles are useful too\n"
with open("count.txt", "w", encoding="utf-8") as f:
    f.write(text)

lines = 0
words = 0
with open("count.txt", encoding="utf-8") as f:
    for line in f:
        lines += 1
        words += len(line.split())

print("lines:", lines)
print("words:", words)
lines: 2 words: 7

The file position

A file object remembers where it is, like a bookmark. When you open a file for reading, the bookmark is at the start. Every read moves it forward. This is why a second read() on the same file gives an empty string: the bookmark is already at the end. If you need to read again, you can call f.seek(0) to move back to the start, or you can simply open the file again. Knowing about the bookmark also explains why readline() gives a different line each time you call it.

Choosing the right tool

For short files such as a small note or a settings file, read() is simple and clear. For a log file with millions of lines, always loop over the file. When you only need the first few lines, call readline() a few times and stop. When you want to change a file, a safe habit is to read the old file, write the result to a new file, and only then replace the old one. This way a bug in your program cannot destroy the original data.

Python converts the line ending of your system to \n when reading text files, so your code can treat every newline the same way.

Python syntax

Syntax
with open("file.txt", "r", encoding="utf-8") as f:
    text = f.read()
Syntax
with open("file.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())
Syntax
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("text\n")
    f.writelines(["a\n", "b\n"])

Real-world applications

  • Reading log files to find errors.
  • Saving notes, to-do lists or reports.
  • Counting words and lines in documents.
  • Loading simple data such as lists of names or words.

Common mistakes

Mistake: Forgetting that each line read from a file ends with a newline character.
Fix: Use line.strip() or line.rstrip("\n") before comparing or printing.
Mistake: Expecting write() or writelines() to add newlines.
Fix: Add "\n" yourself to each string you write.
Mistake: Using mode w when you meant to add to the file.
Fix: Use mode a to append. Mode w erases all old content.
Mistake: Leaving out the encoding, which causes odd characters or errors on another computer.
Fix: Always pass encoding="utf-8" for text files.
Mistake: Calling read() twice and wondering why the second result is empty.
Fix: The file position is at the end after the first read. Use seek(0) to go back, or store the first result.

Important tips

  • Loop over the file object for large files.
  • Use repr() to see hidden newline characters.
  • Use enumerate(f, start=1) to number lines.
  • Write to a new file first when you transform data, so the original is safe.

Key points summary

  • read() returns the whole file, readline() one line, readlines() a list.
  • Looping over the file object is memory friendly.
  • write() and writelines() do not add newlines.
  • Mode w erases, mode a appends.
  • Use encoding="utf-8" for portable text files.

Exam and interview points

  • read(), readline() and readlines() return str, str and list of str.
  • write() returns the number of characters written.
  • Lines keep their trailing newline when read.
  • Mode w truncates the file; mode a appends.

Quick revision

  • read() gives one big string.
  • for line in f is best for big files.
  • strip() removes the newline.
  • write() needs an explicit \n.
  • Use encoding="utf-8".

Frequently asked questions

What is the difference between readlines() and looping over the file?

readlines() builds a list of every line at once. Looping gives one line at a time and uses far less memory.

Why do I get blank lines when I print each line?

Each line already ends with a newline and print adds another. Use line.strip() or print(line, end="").

What does readline() return at the end of the file?

An empty string. A blank line inside the file is "\n", which is not empty.

Why should I give an encoding?

The default encoding changes between systems. UTF-8 makes your program behave the same everywhere.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters