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.
open a file safely
read line by line
write a line (file opened with w or a)
Symbols
| read (default) | ||
| write, deletes old content | ||
| append to the end |
Example
Sum numbers from a file with one number per line:
inside the with block.
Always use with. Then you never have to remember to close the file.
Practise files, errors and modules for free →