File Types, Paths and Open Modes
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,
.datfiles written withpickle. - 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).
| Mode | Meaning | If the file is missing |
|---|---|---|
r | read (default) | FileNotFoundError |
r+ | read and write, from the start | FileNotFoundError |
w | write; erases existing content | created |
w+ | write and read; erases existing content | created |
a | append at the end | created |
a+ | append and read | created |
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
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.