Python File Handling: Working with Various File Formats (txt, csv, json)

Learn Python @ Freshers.in

Python’s file handling capabilities are essential for dealing with various file formats in your programming journey. In this comprehensive guide, we will delve into Python’s file handling functions and libraries, providing detailed explanations, practical examples, and real-world scenarios to help you work seamlessly with different file formats, including txt, csv, and json.

1. Introduction to File Formats

File formats determine how data is stored and structured in files. Common formats include text (txt), comma-separated values (csv), and JavaScript Object Notation (json).

2. Reading and Writing Text Files (txt)

Text files are the simplest file format, containing plain text. Python’s file handling functions make reading from and writing to text files straightforward:

# Writing to a text file
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a text file.")
# Reading from a text file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

3. Working with CSV Files (csv)

CSV (Comma-Separated Values) files are used for tabular data storage. Python’s csv module simplifies working with CSV files:

import csv
# Writing to a CSV file
data = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)
# Reading from a CSV file
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

4. Processing JSON Files (json)

JSON (JavaScript Object Notation) is a widely used data interchange format. Python’s json module allows you to work with JSON files effortlessly:

import json
# Writing to a JSON file
data = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}
with open("data.json", "w") as file:
    json.dump(data, file)

# Reading from a JSON file
with open("data.json", "r") as file:
    loaded_data = json.load(file)
    print(loaded_data)

5. Examples

Let’s explore practical scenarios where different file formats are used:

Example 1: Log File (txt)

# Writing log entries to a log file
import datetime
log_file = "app_log.txt"
with open(log_file, "a") as file:
    timestamp = datetime.datetime.now()
    log_entry = f"{timestamp}: User logged in."
    file.write(log_entry + "\n")

Example 2: Inventory Management (json)

# Managing product inventory using a JSON file
import json
def load_inventory():
    try:
        with open("inventory.json", "r") as file:
            return json.load(file)
    except FileNotFoundError:
        return {}
def save_inventory(inventory):
    with open("inventory.json", "w") as file:
        json.dump(inventory, file)
inventory = load_inventory()
inventory["apple"] = {"quantity": 100, "price": 1.99}
save_inventory(inventory)

6. Best Practices

  • Use appropriate file handling functions and libraries for different formats.
  • Always handle exceptions when reading/writing files.
  • Ensure proper file closing with with statements.
  • Validate and sanitize data before writing to files.

Learn Python Programming

Refer more on python Article here :

Author: user