Python for Artificial Intelligence Advanced 10 minutes

Working with CSV Files

Reading and writing CSV files with the standard library and pandas, paying attention to encoding and delimiters.

Your progress in the track0%

The standard library

import csv

with open("students.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "score"])
    writer.writerow(["Sara", 91])

with open("students.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"], int(row["score"]))

with ensures the file is closed automatically, andnewline="" is recommended by the csv module documentation to avoid extra blank lines.

With pandas

import pandas as pd

df = pd.read_csv("students.csv", encoding="utf-8")
df = pd.read_csv("data.csv", sep=";", na_values=["NA", "-"],
                 parse_dates=["date"])
df.to_csv("out.csv", index=False, encoding="utf-8")

Practical issues

  • Encoding: if the file will be opened in Excel on Windows, use encoding="utf-8-sig" so that Arabic text displays correctly.
  • Delimiter: some regional settings use ; instead of ,.
  • Types: check with df.dtypes; numeric columns that contain text are read as object.
  • Large files: use chunksize to read in chunks, or usecols to read specific columns.

An example of reading in chunks

total = 0
for chunk in pd.read_csv("big.csv", chunksize=100_000):
    total += chunk["amount"].sum()

Lesson terms

Encoding
The way characters are converted to bytes when text is saved and read; the best known is UTF-8.
CSV file
A text file representing a table, in which each line is a row and the values are separated by a delimiter such as a comma.

Abstract

CSV is a text format for storing tabular data, where each line is a row and its values are separated by a delimiter. It can be handled with the csv module in the standard library or with the pandas.read_csv function, which is the most used in data analysis. Important practical issues include the encoding (UTF-8), the delimiter, missing values, and column types.

Review questions

  1. Why does Arabic text sometimes appear garbled when opening a CSV?

    Because of different encodings when saving and reading; the solution is to use encoding="utf-8", or "utf-8-sig" for Excel files.

  2. How do you save a DataFrame without the index column?

    df.to_csv("file.csv", index=False).

Sources and references

  1. csv — CSV File Reading and Writing — Python documentation
  2. pandas.read_csv — pandas documentation
  3. Reading and Writing Files — Python tutorial

Complete the lesson