Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

File Handling

File Handling

# Writing to a file
with open("sample.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a sample file.\n")

# Reading from a file
with open("sample.txt", "r") as file:
    content = file.read()
    print(content)

# Reading line by line
with open("sample.txt", "r") as file:
    for line in file:
        print(line.strip())

# Working with CSV-like data
import csv

# Writing CSV
data = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]
with open("people.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

# Reading CSV
with open("people.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# Delete the created files
import os
os.remove("sample.txt")
os.remove("people.csv")
Hello, World!
This is a sample file.

Hello, World!
This is a sample file.
['Name', 'Age']
['Alice', '25']
['Bob', '30']