File Types, Paths and Open Modes

45 min read Text Files

This is a free course. Log in to run the code exercises and track your progress.

File Types, Paths and Open Modes

Data in variables is lost when a program ends; a file keeps it on disk. Python works with three kinds of file:

  • Text files store characters, line by line, each line ending in a newline (\n). Readable in any editor: .txt, .py.
  • Binary files store bytes exactly as they are in memory, with no line structure. Not human-readable: images, .dat files written with pickle.
  • CSV files are text files of comma-separated values, one record per line, readable by spreadsheet programs.

A path locates a file. An absolute path starts from the root (C:\School\notes.txt or /home/riya/notes.txt); a relative path starts from the program's current folder (notes.txt, data/marks.csv).

ModeMeaningIf the file is missing
rread (default)FileNotFoundError
r+read and write, from the startFileNotFoundError
wwrite; erases existing contentcreated
w+write and read; erases existing contentcreated
aappend at the endcreated
a+append and readcreated

Add b for a binary file: rb, wb, ab, rb+, wb+, ab+. Always close a file, or better, open it with with, which closes it automatically even if an error occurs:

with open("notes.txt", "w") as f:
    f.write("First line\n")
# f is closed here
Python exercise

An in-memory file (io.StringIO, which has the same methods as a file from open()) is opened for writing. Write every input line to it until the line END, each followed by a newline, then print how many characters were written using tell().

import io

f = io.StringIO()   # stands in for open("notes.txt", "w")
while True:
    line = input()
    if line == "END":
        break
    # write line and a newline to f
print(f.tell())
f.close()

Log in to edit and run this code.