Python File Input and Output

Reading and Writing to a File

Python allows you to read from and write to files using the built-in open() function.

Reading a File

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

Writing to a File

file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
  • Use "r" mode to read a file and "w" mode to write to a file. Be sure to close the file after performing operations to free up resources.

Appending to a File

Appending allows you to add content to the end of a file without overwriting the existing data.

Example

file = open("example.txt", "a")
file.write("Appending some text.")
file.close()
  • The "a" mode opens the file for appending. New content is added at the end of the file without altering existing content.

with Context Manager

The with statement is used to simplify file handling. It automatically closes the file when the block of code is exited, even if an error occurs.

Example

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • The with statement handles file closing automatically, ensuring that resources are properly freed.

Comma Separated Values (CSV) Files

CSV (Comma-Separated Values) files are commonly used for storing tabular data. Python’s csv module makes it easy to work with 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)

Writing to a CSV File

import csv

with open("data.csv", "w", newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Tala", 22, "Manila"])
  • The csv.reader reads CSV files row by row, and the csv.writer writes rows to a CSV file. The newline=”” argument prevents extra blank lines in the output file.

JavaScript Object Notation (JSON) Files

JSON (JavaScript Object Notation) is a lightweight data format often used for data interchange between a server and a web application.

Reading a JSON File

import json

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

Writing to a JSON File

import json

data = {
    "name": "Tala",
    "age": 22,
    "city": "Manila"
}

with open("data.json", "w") as file:
    json.dump(data, file)
  • The json.load() function reads JSON data from a file, while json.dump() writes data to a JSON file.

Scroll to Top