Python 提供了强大的工具来读取 CSV 文件,主要使用内置的 csv 模块或第三方库如 pandas。以下是常用方法和示例:
1. 使用 csv 模块
读取 CSV 文件
import csv
# 打开并读取 CSV 文件
with open("example.csv", mode="r", encoding="utf-8") as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
示例文件 example.csv 内容:
Name,Age,City
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
输出结果:
['Name', 'Age', 'City']
['Alice', '30', 'New York']
['Bob', '25', 'Los Angeles']
['Charlie', '35', 'Chicago']
读取 CSV 文件为字典
如果你希望将每行数据映射为字典(表头作为键),可以使用 csv.DictReader。
with open("example.csv", mode="r", encoding="utf-8") as file:
csv_dict_reader = csv.DictReader(file)
for row in csv_dict_reader:
print(row)

最低0.47元/天 解锁文章
4万+

被折叠的 条评论
为什么被折叠?



