Python 基础教程

Python 高级教程

Python 相关应用

Python 笔记

Python FAQ

original icon
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.knowledgedict.com/tutorial/python-read-data-from-csv-file.html

python 读取 csv 文件数据的几种方法

Python 笔记 Python 笔记


python 读取 csv 形式的数据,有非常多的方式,这里主要介绍常用的几种方式,从基于标准库到 pandas 等开源库自带的函数。

基于标准库

使用 python 标准库的 io,主要是借助 open 函数,具体如下:

with open(file_path) as f:
    for i, line in enumerate(f): # 一行一行遍历,i 为遍历行数,从 0 开始,line 每行内容
        line_arr = line.split(',') # 通过 str.split 后返回 list 数据
        if line_arr and len(line_arr) >= 2:
            print(line_arr[1])

使用 pandas

也可以利用 pandas 专为大数据提供的 csv 读取函数 read_csv,示例如下:

import pandas as pd

def read_csv(file_path):
    df = pd.read_csv(file_path)
    print(type(df))  # pandas.core.frame.DataFrame 类
    print(df.shape)  # DataFrame 大小
    print(df.head(5))  # 打印头部 5 行
    print(df.tail(5))  # 打印尾部 5 行
    print(type(df['搜索词']))  # pandas.core.series.Series 类
    for idx, row in df.iterrows():  # 遍历 DataFrame
        print(idx, row['搜索词'])