Read CSV Files in Python

To read data from a CSV file in Python, you can use the built-in csv module. First, you need to import the csv module and then use the open() function to open the CSV file.

Here is an example code that shows how to read data from a CSV file.

import csv

# 打开CSV文件
with open('data.csv', 'r') as file:
    # 创建CSV读取器
    csv_reader = csv.reader(file)

    # 遍历每行数据
    for row in csv_reader:
        # 打印每行数据
        print(row)

In this example, assuming the CSV file is named “data.csv,” we start by opening the file using the open() function with the mode “r” (read mode). Then, we create a CSV reader object using csv.reader() to read the data line by line from the file. Lastly, we use a for loop to iterate through each row of data and print it out.

You can skip the header row in a CSV file by using the next() function if the first row contains column names.

import csv

# 打开CSV文件
with open('data.csv', 'r') as file:
    # 创建CSV读取器
    csv_reader = csv.reader(file)

    # 跳过表头行
    next(csv_reader)

    # 遍历每行数据
    for row in csv_reader:
        # 打印每行数据
        print(row)

In this example, the next() function was used to skip the first line of data.

Additionally, if each line of data in the CSV file contains a different number of fields, you can use the csv.DictReader() function to create a dictionary reader object to read the data and store it as a dictionary. Here is an example code:

import csv

# 打开CSV文件
with open('data.csv', 'r') as file:
    # 创建字典读取器
    csv_reader = csv.DictReader(file)

    # 遍历每行数据
    for row in csv_reader:
        # 打印每行数据
        print(row)

In this example, a dictionary reader object was created using the csv.DictReader() function. This allows each row of data to be stored in dictionary format, with the keys representing column names and the values representing the corresponding data values.

bannerAds