logo

How to Load CSV Files in Python 📂Programing

How to Load CSV Files in Python

Description

There are four main ways to read a CSV file in Python: (1) using only built-in I/O, (2) the standard library csv module, (3) pandas, and (4) numpy.

Code

Let’s open the following CSV file.

Built-in I/O

Load the CSV file as a text object.

>>> x = open('3784.csv', 'r', encoding='utf-8')

>>> x
<_io.TextIOWrapper name='3784.csv' mode='r' encoding='utf-8'>

>>> for line in x: print(line)
...
a,가,1

b,나,2

c,다,3

d,라,4

csv

Obtain each row as a list.

>>> import csv

>>> with open('3784.csv', newline="", encoding='utf-8') as f:
...     reader = csv.reader(f)
...     for row in reader:
...             print(row)
...
['a', '가', '1']
['b', '나', '2']
['c', '다', '3']
['d', '라', '4']

pandas

Load the CSV file as a DataFrame.

>>> import pandas as pd

>>> df = pd.read_csv('3784.csv')

>>> type(df)
<class 'pandas.core.frame.DataFrame'>

>>> df
   a  가  1
0  b  나  2
1  c  다  3
2  d  라  4

>>> print(df.columns)
Index(['a', '가', '1'], dtype='object')

numpy

If all entries are numeric, you can also open it with numpy. Load as a NumPy array.

>>> import numpy as np

>>> data = np.loadtxt('3784.csv', delimiter=",", encoding="cp949")

>>> type(data)
<class 'numpy.ndarray'>

>>> data
array([1., 2., 3., 4., 5., 6., 7., 8., 9.])

Environment

  • OS: Windows 11
  • Version: Python 3.10.11, pandas==2.2.3, numpy==1.26.4