TExcelTAD
Home › Python › Python File Handling

Python File Handling

Reading and writing files lets your programs save data between runs, process logs and reports, and exchange information with other software. Python's built-in open() function is the entry point.

Note: In the browser, these examples run against an in-memory file system provided by Pyodide, so nothing touches your disk. If you run them on your own computer they create a real file named exceltad_demo.txt in the current folder — and each example deletes it again at the end with os.remove().

Opening a file

python
f = open(filename, mode, encoding="utf-8")
Mode Meaning If the file doesn't exist
"r" read (default) FileNotFoundError
"w" write — erases existing content creates it
"a" append to the end creates it
"x" create — fail if it exists creates it
"r+" read and write FileNotFoundError
add "b" binary mode, e.g. "rb" for images —

Tip: Always pass encoding="utf-8" for text files. Otherwise Python uses a platform default, and text with accents or emoji may break on another computer.

The with statement

Files must be closed when you're done, or data may not be written out. The with statement closes the file automatically, even if an error occurs:

python · try it yourself
import os

with open("exceltad_demo.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
    f.write("second line\n")

print("closed?", f.closed)

with open("exceltad_demo.txt", encoding="utf-8") as f:
    content = f.read()
print(repr(content))

os.remove("exceltad_demo.txt")
closed? True
'first line\nsecond line\n'

write() doesn't add newlines for you — include \n yourself.

Reading a file

There are several ways to read, depending on how much you need at once:

Method Returns
f.read() the whole file as one string
f.read(n) the next n characters
f.readline() the next line (including \n)
f.readlines() a list of all lines
for line in f: one line at a time — best for large files
python · try it yourself
import os

with open("exceltad_demo.txt", "w", encoding="utf-8") as f:
    f.write("apple,3\nbanana,12\ncherry,7\n")

with open("exceltad_demo.txt", encoding="utf-8") as f:
    print(f.readline().strip())       # first line only
    for line in f:                    # the remaining lines
        name, qty = line.strip().split(",")
        print(f"{name:>8}: {int(qty):>3}")

with open("exceltad_demo.txt", encoding="utf-8") as f:
    print(f.readlines())

os.remove("exceltad_demo.txt")
apple,3
  banana:  12
  cherry:   7
['apple,3\n', 'banana,12\n', 'cherry,7\n']

The file object remembers its position: after readline() read the first line, the for loop continued from the second.

Writing and appending

Mode "w" replaces the file's content; mode "a" adds to the end. writelines() writes a list of strings, and print(..., file=f) is a convenient way to write formatted lines:

python · try it yourself
import os

with open("exceltad_demo.txt", "w", encoding="utf-8") as f:
    f.writelines(["Mon: 5 km\n", "Tue: 3 km\n"])

with open("exceltad_demo.txt", "a", encoding="utf-8") as f:
    print("Wed: 8 km", file=f)

with open("exceltad_demo.txt", encoding="utf-8") as f:
    lines = f.read().splitlines()
print(lines)
total = sum(int(line.split()[1]) for line in lines)
print("Total:", total, "km")

os.remove("exceltad_demo.txt")
['Mon: 5 km', 'Tue: 3 km', 'Wed: 8 km']
Total: 16 km

Checking for and deleting files

python · try it yourself
import os

name = "exceltad_demo.txt"
print(os.path.exists(name))

with open(name, "x", encoding="utf-8") as f:
    f.write("created once")

try:
    open(name, "x")
except FileExistsError:
    print("Mode 'x' refuses to overwrite")

print(os.path.exists(name), os.path.getsize(name), "bytes")
os.remove(name)
print(os.path.exists(name))

try:
    open("no_such_file.txt", encoding="utf-8")
except FileNotFoundError as err:
    print("FileNotFoundError:", err.filename)
False
Mode 'x' refuses to overwrite
True 12 bytes
False
FileNotFoundError: no_such_file.txt

pathlib — the modern way

The pathlib module treats paths as objects with handy methods. For small files, write_text() and read_text() do the open-write-close dance in one call:

python · try it yourself
from pathlib import Path

p = Path("exceltad_demo.txt")
p.write_text("Hello from pathlib\n", encoding="utf-8")
print(p.read_text(encoding="utf-8").strip())
print(p.name, p.stem, p.suffix)
print(Path("reports") / "2025" / "summary.csv")
p.unlink()                      # delete the file
print(p.exists())
Hello from pathlib
exceltad_demo.txt exceltad_demo .txt
reports/2025/summary.csv
False

The / operator joins path parts using the right separator for the operating system (the output shows /; on Windows it would be \).

Test yourself

What happens to existing content when you open a file with mode "w"?

  1. New text is appended
  2. It is erased
  3. Python raises an error
  4. It becomes read-only

Why is with open(...) as f: recommended?

  1. It reads faster
  2. It automatically closes the file, even on errors
  3. It's required for writing
  4. It encrypts the file

Which is the most memory-friendly way to process a huge text file line by line?

  1. f.read()
  2. f.readlines()
  3. for line in f:
  4. list(f)