Reading and Writing Files
Storing and retrieving data from files on the hard drive (or other storage media) is a fundamental skill. If you only use variables, all your data will disappear as soon as the program ends.
The open() Function
The built-in open() function is the key to handling text files in Python. It takes two key parameters: the file name and the "mode" (the purpose of opening).
Main Modes
"r"(Read): Default mode. Opens a file for reading. Causes an error if the file does not exist."w"(Write): Opens a file for writing. CAREFUL! If the file already exists, it will overwrite it (erasing its previous content). If it does not exist, it will create it."a"(Append): Opens a file for writing, but instead of erasing the previous content, it starts writing at the end of the file. It creates it if it does not exist.
Writing to a File (w and a)
# 'w' MODE: Opening (or creating) the file for writing
file = open("my_diary.txt", "w")
file.write("This is the first entry in my diary.\n")
# ALWAYS CLOSE THE FILE WHEN YOU FINISH!
file.close()
# 'a' MODE: Adding a new line without erasing the previous one
file = open("my_diary.txt", "a")
file.write("This is my second note.\n")
file.close()
Reading from a File (r)
file = open("my_diary.txt", "r")
# .read() reads the entire file at once
content = file.read()
print("FULL CONTENT:")
print(content)
file.close()
The "Safe" Way (The with block)
What happens if an error occurs and your program crashes before reaching file.close()? The file could be left corrupt in memory or be inaccessible to other programs.
The best practice (recommended by Python) is to use the with block. This magic mechanism takes care of calling .close() automatically when you finish using the file, even if an error occurs.
# With 'with', you don't need to worry about .close()
with open("my_diary.txt", "r") as file:
# Read line by line
for line in file:
print(f"Read line: {line.strip()}")