top of page

Notes on handling CSV and Arrays in Python

May 21
2 min read

Last time, when I was researching Excel operations, I confirmed that Python can read and handle Excel files as objects by using the openpyxl library. This allowed me to manipulate Excel contents within Python.


Python

import openpyxl
wb = openpyxl.load_workbook("C:/temp/aaa.xlsx")

To become more familiar with Python, I looked into how to handle arrays and CSV files as a new subject.


Python

data = [
    {"name": "A", "qty": 10},
    {"name": "B", "qty": 20}
]
for d in data:
    print(d["name"], d["qty"])

-------

Execution Result:

A 10 B 20



CSV

Regarding CSV, it seems similar to VBA. However, since I do not have my Python environment at home with me while I am away, I had to operate it on the web. Because I cannot access actual CSV files, I tried embedding the CSV pseudo-randomly (or rather, simulating it).

------

Python

import csv
with open("C:\Temp/test.csv") as f:
    for row in csv.reader(f):
        print(row)

------

Python

import csv
import io
data = io.StringIO("""a,b,c
1,2,3
4,5,6
""")
for row in csv.reader(data):
    print(row)

``

Execution Result:

['a', 'b', 'c']

['1', '2', '3']

['4', '5', '6']


In the Paiza environment, I cannot place actual files (CSV). Therefore, instead, I write the contents of the CSV as a string within the code and pass it to csv.reader by making it "pretend" to be a file. The io.StringIO function serves that purpose. Also, since I wanted to output with headers instead of just the result, I looked into csv.reader and csv.DictReader.


ーーー

Python

import csv
import io
data = io.StringIO("""name,qty
apple,10
orange,20
""")
for row in csv.DictReader(data):
    print(row["name"], row["qty"])

ーーー

Execution Result:

apple 10 orange 20


The difference between csv.reader and csv.DictReader:

  • csv.reader: Simply splits by commas and makes each row a "list." It does not have the concept of column names.

  • csv.DictReader: The first row is the header (label), and the following rows are the data. Each row becomes "data with labels."

By the way, I tried it with a CSV I made at home.


Python

>>> import csv
>>> with open("C:\tmp/test.csv") as f:
...     for row in csv.reader(f):
...             print(row)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument: 'C:\tmp/test.csv'

I had no idea what was wrong. Upon investigation, it was because the \t in the file path string was interpreted as a "tab," a special character (escape sequence). In Python, if a specific character follows a \ (backslash) in a string, it is treated as a special character. In this case, the C:\t... part was converted to a tab character, and it was not recognized as a correct file path. In short, using a forward slash would have worked. Alternatively, adding r before the string allows \ to be treated as a literal character rather than an escape sequence. See the r in the red text below.


Python

>>> import csv
>>> with open(r"C:\tmp/test.csv") as f:
...     for row in csv.reader(f):
...             print(row)
...

Execution Result:

['Name', 'Age', 'Gender']

['Taka', '47', 'M']

['Mika', '23', 'F']

['Uji', '35', 'M']

['Iris', '19', 'F']


 
 
 

Comments


bottom of page