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

王林
Release: 2024-04-04 09:33:01
Original
931 people have browsed it

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
Copy after login

Step 2: Open the CSV file

Use theopen()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:
Copy after login

Step 3: Read and parse CSV data

Use thecsv.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: # 处理每一行数据
Copy after login

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])
Copy after login

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])
Copy after login

This code will output something similar to the following:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!