Types of Files in Python

In Python, files can be categorized based on their content and how they are processed. The primary types of files include:

1. Text Files

Text files contain plain text and can be read or written using Python's built-in file handling functions. These files have extensions such as .txt, .csv, and .json.

Example of Reading and Writing a Text File

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

Output

Hello, World!
This is a text file.

2. Binary Files

Binary files contain data in a format that is not human-readable. These files can include images, audio files, and executable files. They are processed using the rb (read binary) and wb (write binary) modes.

Example of Reading and Writing a Binary File

# Writing to a binary file
        data = bytes([120, 3, 255, 0, 100])
        with open("example.bin", "wb") as file:
            file.write(data)
        
        # Reading from a binary file
        with open("example.bin", "rb") as file:
            binary_content = file.read()
            print(list(binary_content))

Output

[120, 3, 255, 0, 100]

3. CSV Files

CSV (Comma-Separated Values) files are a type of text file that stores tabular data. They can be read and written using the csv module in Python.

Example of Reading and Writing CSV Files

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

Output

['Name', 'Age']
['Alice', '30']
['Bob', '25']

4. JSON Files

JSON (JavaScript Object Notation) files are used to store data in a structured format. They can be easily read and written using the json module in Python.

Example of Reading and Writing JSON Files

import json
        
        # Writing to a JSON file
        data = {"name": "Alice", "age": 30}
        with open("example.json", "w") as file:
            json.dump(data, file)
        
        # Reading from a JSON file
        with open("example.json", "r") as file:
            json_content = json.load(file)
            print(json_content)

Output

{'name': 'Alice', 'age': 30}

Conclusion

Python provides various file types to handle different data formats, including text files, binary files, CSV files, and JSON files. Understanding how to work with these file types is essential for effective file handling in Python.