Loading...
Loading...

File Handling in Python

Python allows you to read from and write to files easily. This tutorial covers text, CSV, and JSON files, as well as how to use context managers (with statements) for managing file resources efficiently.

1. Reading and Writing Text Files

Text files are simple to read and write in Python. Here's how to open, read, and write text files:

Reading a Text File

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

Explanation: The with statement opens the file and automatically closes it after the block. "r" is the mode for reading.

Writing to a Text File

with open("example.txt", "w") as file:
    file.write("Hello, world!")

Explanation: "w" mode opens the file for writing. If the file exists, it will overwrite the content; otherwise, it creates a new file.

Text Files Quiz

What happens if you open a non-existent file in "r" mode?

  • FileNotFoundError is raised
  • Python creates a new empty file
  • It silently fails

How do you append to a file without overwriting existing content?

  • open("file.txt", "w")
  • open("file.txt", "a")
  • open("file.txt", "r+")

2. Working with CSV Files

CSV files are commonly used for data storage. Python's csv module helps with reading and writing CSV files.

Reading a CSV File

import csv

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Explanation: csv.reader reads each row as a list of values, making it easy to process CSV data.

Writing to a CSV File

import csv

data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]

with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

Explanation: csv.writer writes data as rows in the CSV file. newline="" ensures no extra blank rows.

CSV Files Quiz

Why is newline="" important when writing CSV files?

  • It makes the file smaller
  • It prevents extra blank lines between rows
  • It's required for CSV file validation

How would you read a CSV file with headers into a dictionary?

  • csv.reader()
  • csv.DictReader()
  • csv.header_reader()

3. Working with JSON Files

JSON files are popular for storing structured data. Python's json module makes it easy to read and write JSON files.

Reading a JSON File

import json

with open("data.json", "r") as file:
    data = json.load(file)
    print(data)

Explanation: json.load reads and parses JSON data, converting it into Python dictionaries and lists.

Writing to a JSON File

import json

data = {"name": "Alice", "age": 30}

with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

Explanation: json.dump writes Python data to a JSON file. The indent parameter formats the JSON for readability.

JSON Files Quiz

What Python data type does JSON most closely resemble?

  • List
  • Dictionary
  • Tuple

What does the indent parameter do in json.dump()?

  • Adds pretty-printing with spaces
  • Compresses the JSON output
  • Validates the JSON structure

4. Using Context Managers

Using with statements (context managers) ensures that files are closed automatically after processing, even if errors occur. This practice is safer and more efficient.

Example

with open("example.txt", "r") as file:
    data = file.read()
    # File is automatically closed after this block

Note: This approach prevents memory leaks and avoids having to manually close files.

Context Managers Quiz

What's the main advantage of using with for file handling?

  • It makes files open faster
  • It ensures files are properly closed
  • It allows multiple files to open at once

What happens if an exception occurs inside a with block?

  • The file is still closed properly
  • The file remains open
  • The program crashes immediately
0 Interaction
2.2K Views
Views
11 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home