PYTHON

  minte9
REMEMBERS




Reader

p371 The CSV format it's just a text file with comma-separated values.
 
"""CSV reader:
Always use csv module for reading and writing CSV files.
It's not enough to just split the text file by comma (,)
Maybe files use escape characters to allowed commas as part of values.

The most convenient to access values in the reader object ...
is to convert it to a list
"""
import csv, pathlib
DIR = pathlib.Path(__file__).resolve().parent


"""Convert the csv reader to a list:
"""
with open(DIR / 'data/file1.csv') as file:
    reader = csv.reader(file)
    data = list(reader)
    assert data[0][0] == '11'
    assert data[0][1] == '12'


"""With large files you'll want a for loop:
"""
with open(DIR / 'data/file1.csv') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
            # ['11', '12', '12']
            # ['21', '22', '23']
            # ['31', '32', '33']

Writer

p374 Wth writer object you can write data to a CSV file.
 
"""CSV writer:
Use open() method and pass it 'w' argument.
On windows you'll also need to pass newline='' argument.
"""
import csv, pathlib
DIR = pathlib.Path(__file__).resolve().parent

# Writer
with open(DIR / 'data/file2.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow([11, 12, 13])
    writer.writerow([21, 22, 23])
    writer.writerow([31, 32, 33])

# Check
with open(DIR / 'data/file2.csv') as file:
    reader = csv.reader(file)
    data = list(reader)
    assert data[1][1] == '22'
    assert data[2][2] == '33'

Dictionary

For CSV files that contain header you can use dictionary.
 
"""CSV Dict:
It is often more convenient to work with ...
DictReader and DictWriter objects.
You can pass headers values as arguments.
"""
import csv, pathlib
from typing import AnyStr
DIR = pathlib.Path(__file__).resolve().parent

# Dictionary Reader
with open(DIR / 'data/fileH1.csv') as file:
    dr = csv.DictReader(file)
    for row in dr:
        print(row['A'], row['B'], row['C'])
            # 11 12 13
            # 21 22 23
            # 31 32 33

# Dictionary Writer
with open(DIR / 'data/fileH2.csv', 'w', newline='') as file:
    dw = csv.DictWriter(file, ['A', 'B', 'C'])
    dw.writeheader()
    dw.writerow({'A':11, 'B':12, 'C':13})
    dw.writerow({'A':21, 'B':22, 'C':23})
    dw.writerow({'A':31, 'B':32, 'C':33})

# Check the file
A = []
with open(DIR / 'data/fileH2.csv') as file:
    dr = csv.DictReader(file)
    for row in dr:
        A.append(row['A'])
print(A)
    # ['11', '21', '31']

Questions     github Storage
Json
        A B C D E F
🔔
1/1