python 六 文件操作 读取csv文件

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)

输出结果:

{'Name': 'Alice', 'Age': '30', 'City': 'New York'}
{'Name': 'Bob', 'Age': '25', 'City': 'Los Angeles'}
{'Name': 'Charlie', 'Age': '35', 'City': 'Chicago'}

2. 使用 pandas

pandas 是处理表格数据的强大工具,适合读取和操作 CSV 文件。

读取 CSV 文件

import pandas as pd

# 使用 pandas 读取 CSV 文件
df = pd.read_csv("example.csv")
print(df)

输出结果:

     Name  Age         City
0   Alice   30     New York
1     Bob   25  Los Angeles
2  Charlie   35      Chicago

访问特定列或行

# 访问列
print(df["Name"])

# 访问行
print(df.iloc[1])  # 按索引访问

数据过滤

# 筛选 Age 大于 30 的行
filtered_df = df[df["Age"] > 30]
print(filtered_df)

3. 分块读取大文件

对于大 CSV 文件,可以分块读取,避免一次性加载占用过多内存。

使用 pandas 分块读取

# 分块读取,每次读取 100 行
chunk_size = 100
for chunk in pd.read_csv("large_file.csv", chunksize=chunk_size):
    print(chunk)

4. 写入 CSV 文件

使用 csv 模块写入

import csv

# 数据写入 CSV 文件
data = [
    ["Name", "Age", "City"],
    ["Alice", 30, "New York"],
    ["Bob", 25, "Los Angeles"],
    ["Charlie", 35, "Chicago"]
]

with open("output.csv", mode="w", encoding="utf-8", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

使用 pandas 写入

import pandas as pd

# 创建 DataFrame 并写入 CSV
data = {
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [30, 25, 35],
    "City": ["New York", "Los Angeles", "Chicago"]
}
df = pd.DataFrame(data)
df.to_csv("output.csv", index=False, encoding="utf-8")

5. 处理带分隔符的 CSV 文件

如果文件的分隔符不是逗号(如 ;),可以指定 delimiter 参数。

使用 csv 模块

with open("example_semicolon.csv", mode="r", encoding="utf-8") as file:
    csv_reader = csv.reader(file, delimiter=";")
    for row in csv_reader:
        print(row)

使用 pandas

df = pd.read_csv("example_semicolon.csv", delimiter=";")
print(df)

6. 示例:合并多个 CSV 文件

使用 pandas 合并多个文件

import pandas as pd
import glob

# 获取所有 CSV 文件路径
csv_files = glob.glob("data/*.csv")

# 合并所有 CSV 文件
dataframes = [pd.read_csv(file) for file in csv_files]
merged_df = pd.concat(dataframes, ignore_index=True)

# 保存到新文件
merged_df.to_csv("merged.csv", index=False)

小结

  • csv 模块:适合简单的读取和写入操作,灵活性高。
  • pandas:功能强大,支持数据分析和复杂操作。
  • 大文件:使用分块读取或生成器处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十方来财

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值