Home >Backend Development >Python Tutorial >Teach you step by step how to read CSV files with Python

Teach you step by step how to read CSV files with Python

王林
王林Original
2024-04-04 09:33:011124browse

To read a CSV file, you can use Python's csv library. The specific steps are as follows: Import the csv library. Open the CSV file using the open() function. Use the csv.reader() function to read the file content and parse it into a reader object. Iterate over the reader object to read CSV data line by line.

Teach you step by step how to read CSV files with Python

Teach you step by step to read CSV files with Python

CSV (comma separated values) files are a common data Format for storing tabular data. Python provides multiple methods to read CSV files, and this article will introduce one of the simplest and most commonly used methods.

Step 1: Import the necessary libraries

First, you need to import the necessary libraries to process CSV files.

import csv

Step 2: Open the CSV file

Use the open() function to open the CSV file to be read. Specify the file name and open mode ('r' means read-only).

with open('data.csv', 'r') as f:

Step 3: Read and parse CSV data

Use the csv.reader() function to read the file content and parse it into a reader object. You can then iterate over the object to read the data line by line.

reader = csv.reader(f)
for row in reader:
    # 处理每一行数据

Step 4: Process each row of data

Each row of data is a list that contains all column values ​​of the row. Individual values ​​can be accessed using indexes.

for row in reader:
    print(row[0], row[1], row[2])

Practical case

The following is a code example that reads a CSV file named "data.csv" and prints the first three lines:

import csv

with open('data.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row[0], row[1], row[2])

This code will output something similar to the following:

Name,Age,Height
John,30,180
Jane,25,170
Mary,28,165

The above is the detailed content of Teach you step by step how to read CSV files with Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn