Text Files · 5 / 17 Theory

Common mistakes with text files

Files introduce errors that do not exist when you only work with variables. These are the most common ones.

1. FileNotFoundError

The file is not where Python is looking for it. Relative paths are resolved from the working folder, not from the program's folder. Check the name (and the capitals!), the extension and the folder. To debug:

import os
print(os.getcwd())               # current working folder
print(os.path.exists("data.txt"))

2. Opening with "w" a file you wanted to read or keep

open(name, "w") empties the file instantly, even if you write nothing. A mode mistake can destroy your data. If you want to add, use "a".

3. Forgetting the \n when writing

with open("a.txt", "w", encoding="utf-8") as f:
    f.write("one")
    f.write("two")
# a.txt contains: onetwo

4. Extra blank lines when showing

for line in f:
    print(line)                  # two line breaks per line
    print(line.rstrip("\n"))      # correct
    print(line, end="")           # also correct

5. Reading the same file twice

After read(), the next read() or a for over the same object returns nothing: it is already at the end. Store the content in a variable or open the file again.

6. Writing a number without converting it

f.write(42)
# TypeError: write() argument must be str, not int

f.write(str(42))   # correct

7. Using the file outside the with

with open("a.txt", "r", encoding="utf-8") as f:
    pass

f.read()
# ValueError: I/O operation on closed file.

8. Not specifying the encoding

Without encoding="utf-8", Python uses the system's encoding, and a text with accents may look fine on your computer and wrong on another (or raise UnicodeDecodeError).

9. Strange characters at the end

If you compare a line with a value and it never matches, check whether it carries the final \n: "hello\n" == "hello" is False.

Handling errors with try / except

name = input()
try:
    with open(name, "r", encoding="utf-8") as f:
        print(f.read())
except FileNotFoundError:
    print("The file cannot be found")

Checklist

  • Is the mode the right one (r, w or a)?
  • Do I write \n at the end of each line with write?
  • Do I remove the \n when I am going to process or compare the text?
  • Do I use with and encoding="utf-8"?
  • Do I convert to str what is not text?