본문 바로가기

Language/Python

[csv] Read files

1. What does csv library do?

The Python's library called csv allows data from various format to be imported in our program.

 

2. How to use it?

2.1 Open files one by one

First, open the file we want using open buillt-in function. And then, make reader object using reader method from csv library. 

 

We should close the file we open after we make reader obejct. The final data we will use will be stored in list of list when we encase reader object into list function.

 

opened_file = open("csv_file.csv") 
from csv import reader
read_file = reader(opened_file) 
opened_file.close() 
data = list(read_file)

 

2.2 Open and close file automatically

When we open a file, we must perform a closing operation. Context manager automatically opens and colses files. We can also write or add data to a file, and we can open the file by specifying an encoding method.

 

import csv
with open("csv_file.csv", mode="r", encoding = encoding) as file : 
    rows = list(csv.reader(file))