All courses › Programming with Python › Reading and writing files

Reading and writing files

Programs often need to save data or read in measurements. In Python you open a file with open, and with closes it automatically when the block ends, even if something goes wrong. Mode r reads, w overwrites and a appends to the end.

with open("data.txt") as f:\texttt{with open("data.txt") as f:}open a file safely
for line in f:\texttt{for line in f:}read line by line
f.write(text + "\n")\texttt{f.write(text + "\textbackslash n")}write a line (file opened with w or a)

Symbols

r\texttt{r}read (default)
w\texttt{w}write, deletes old content
a\texttt{a}append to the end

Example

Sum numbers from a file with one number per line:

sum(float(x) for x in f)\texttt{sum(float(x) for x in f)} inside the with block.

Always use with. Then you never have to remember to close the file.
Practise files, errors and modules for free →

← Mutable objects and references · Error handling →

Part of Programming with Python: Files, errors and modules.