CSV#

import csv
import tempfile
from pathlib import Path
from collections import namedtuple

Writing#

To write data to a CSV file, you may first open a file and create a CSV writer using csv.writer(). Then, use the writerow() method to write a single row of data, and writerows() to write multiple rows of data.

tmp_dir = tempfile.TemporaryDirectory()

header = ("id", "name")

data = [
    (1, "Isaac"),
    (2, "John"),
]

# CSV file path
csv_file_path = Path(tmp_dir.name).joinpath("data.csv")

with open(csv_file_path, "w") as f:

    # Create a CSV writer
    writer = csv.writer(f)

    # Write the header
    writer.writerow(header)

    # Write the data
    writer.writerows(data)

# Read CSV file
with open(csv_file_path, "r") as f:
    content = f.read()

# Print CSV file content
print(content)

tmp_dir.cleanup()
id,name
1,Isaac
2,John
tmp_dir = tempfile.TemporaryDirectory()

Sample = namedtuple(
    "Sample",
    (
        "id",
        "name",
    ),
)

header = Sample._fields

data = [
    Sample(id=1, name="Isaac"),
    Sample(id=2, name="John"),
]

# CSV file path
csv_file_path = Path(tmp_dir.name).joinpath("data.csv")

with open(csv_file_path, "w") as f:

    # Create a CSV writer
    writer = csv.writer(f)

    # Write the header
    writer.writerow(header)

    # Write the data
    writer.writerows(data)

# Read CSV file
with open(csv_file_path, "r") as f:
    content = f.read()

# Print CSV file content
print(content)

tmp_dir.cleanup()
id,name
1,Isaac
2,John

Reading#

tmp_dir = tempfile.TemporaryDirectory()

header = ("id", "name")

data = [
    (1, "Isaac"),
    (2, "John"),
]

# CSV file path
csv_file_path = Path(tmp_dir.name).joinpath("data.csv")

with open(csv_file_path, "w") as f:

    # Create a CSV writer
    writer = csv.writer(f)

    # Write the header
    writer.writerow(header)

    # Write the data
    writer.writerows(data)

# Read CSV file
with open(csv_file_path, "r") as f:

    # Create a CSV reader
    reader = csv.reader(f)

    for row in reader:
        print(row)


tmp_dir.cleanup()
['id', 'name']
['1', 'Isaac']
['2', 'John']