Opening and Closing Files
Python reads and writes files through a file object. open(path, mode) returns that object. Mode 'r' reads text, 'w' writes (and wipes an existing file), 'a' appends. Always close() the file, or use with open(...) as f: so Python closes it even if an error occurs.
A path is a string. If the file is in the same folder as the program, the filename alone is enough. Missing files raise FileNotFoundError when you open them for reading.
Which open mode erases an existing file then writes new text?
Read versus Write
Read
f.read() returns the whole file as one string. f.readlines() returns a list of lines, each usually ending with \n. You can also loop for line in f:.Write
f.write(text) writes a string. To save a list, join the items or loop and write each one, adding \n if you want separate lines. Write mode does not add a newline for you.
f.readlines() returns
Reading line by line
Large files are usually processed one line at a time:
readline()returns the next line, including its\n, or an empty string at the end of the filefor line in f:visits every line in turnstrip()removes the newline before a line is compared, printed or converted
f = open("names.txt", "r")
for line in f:
print(line.strip())
f.close()Asha Ben Chloe
Every line is read as a string, so convert it with int() or float() before doing arithmetic.
Appending to a file
Mode "a" adds new text after the existing content, so earlier data is kept. If the file does not exist, Python creates it. Appending suits:
- a log of events, one per line
- adding a new high score without losing the old ones
- collecting survey replies over several runs
log = open("log.txt", "a")
log.write("Login: user42\n")
log.close()Running this twice leaves two identical lines at the end of log.txt. Numbers must be converted with str() before they are written.
Complete! Ready to test your knowledge?
File handling in Python
- Opening and Closing Files
- Read versus Write
- Reading line by line
- Appending to a file