Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

MODULE 9: File Handling

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.

1. File Modes

When opening a file, you must specify the mode, which tells Python what you intend to do.

ModeDescription
'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.

2. Reading, Writing, & Appending

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)

3. Working with CSV & TXT

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])

4. JSON Handling

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$ String
  • json.loads(): String $\rightarrow$ Dictionary

Example:

Python

import json

user = {"name": "Bob", "active": True}
json_string = json.dumps(user) # Convert to JSON string
print(json_string)

5. Pickle Serialization

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)

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥