In Module 9, we learn how to make data persistent. Up until now, variables disappear when the program stops. File handling allows you to save data to the hard drive so it’s there when you come back.
When opening a file, you must specify the mode, which tells Python what you intend to do.
| Mode | Description |
'r' | Read (Default): Opens for reading. Error if file doesn’t exist. |
'w' | Write: Creates a new file or overwrites an existing one. |
'a' | Append: Adds data to the end of an existing file. |
'r+' | Read/Write: Opens the file for both reading and writing. |
The safest way to handle files is using the with statement. It automatically closes the file for you, even if an error occurs.
Example:
Python
# WRITING
with open("note.txt", "w") as file:
file.write("Hello Python!\n")
# APPENDING
with open("note.txt", "a") as file:
file.write("Adding a new line.")
# READING
with open("note.txt", "r") as file:
content = file.read()
print(content)
TXT files are for plain text. CSV (Comma Separated Values) files are used for tabular data (like Excel). Python has a built-in csv module to handle them.
Example (CSV):
Python
import csv
# Writing to a CSV
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Score"])
writer.writerow(["Alice", 95])
JSON (JavaScript Object Notation) is the standard format for exchanging data over the web. The json module converts Python dictionaries to JSON strings and vice versa.
json.dumps(): Dictionary $\rightarrow$ Stringjson.loads(): String $\rightarrow$ DictionaryExample:
Python
import json
user = {"name": "Bob", "active": True}
json_string = json.dumps(user) # Convert to JSON string
print(json_string)
While JSON is for text-based data exchange, Pickle is used to serialize complex Python objects (like custom class instances or lists) into a binary format.
Note: Only unpickle data you trust, as it can execute arbitrary code during unpickling.
Example:
Python
import pickle
data = {"id": 1, "complex_list": [1, 2, 3]}
# Serialize (Save to binary file)
with open("data.pkl", "wb") as f:
pickle.dump(data, f)
# Deserialize (Load from binary file)
with open("data.pkl", "rb") as f:
loaded_data = pickle.load(f)