File manipulation is an essential skill for any Python programmer. Whether you are reading system logs, processing CSV spreadsheets, or working with JSON APIs, knowing how to work with files is fundamental. In this complete guide, you will learn how to read, write, and manipulate the main file formats: TXT, CSV, and JSON.

Files are the most common way to persist data. In the Python Universe, imagine files as "data capsules" that navigate between different systems and eras, allowing information to survive beyond the program's execution.

  • 📄 TXT - Plain text files (logs, configurations)
  • 📊 CSV - Spreadsheets and tabular data
  • 🗂️ JSON - APIs, structured configurations

📄 Text Files (TXT)

Reading TXT Files

Python offers several ways to read text files. The safest way is to use the with context manager, which closes the file automatically:

# Recommended way - with statement
with open('log_book.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

Opening Modes

Mode Description
'r' Read (default)
'w' Write (overwrites)
'a' Append (adds to the end)

Different Reading Methods

# 1. Read complete file
with open('log.txt', 'r', encoding='utf-8') as f:
    full_text = f.read()

# 2. Read line by line
with open('log.txt', 'r', encoding='utf-8') as f:
    for line in f:
        print(line.strip())

📊 CSV Files (Comma-Separated Values)

CSV is the standard format for spreadsheets and tabular data. Python has a native csv module that makes the job much easier.

Reading CSV

import csv

with open('planets.csv', 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

🗂️ JSON Files (JavaScript Object Notation)

JSON is the most used format for APIs and structured data exchange. It is practically identical to Python dictionaries!

Writing JSON

import json

data = {"name": "Python", "version": 3.12}
with open('config.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=4)

🚀 Conclusion

Now that you master file manipulation, explore related topics like Python Lists or Dictionaries. For more details, check the official Python documentation on file handling.