Python面试题:在 Python 中,如何处理 CSV 文件?

在 Python 中处理 CSV 文件通常使用 csv 模块。以下是一些常见的操作及示例代码:

读取 CSV 文件

import csv

def read_csv(file_path):
    with open(file_path, mode='r', newline='', encoding='utf-8') as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)

# 示例用法
file_path = 'example.csv'
read_csv(file_path)

写入 CSV 文件

import csv

def write_csv(file_path, data):
    with open(file_path, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerows(data)

# 示例用法
file_path = 'output.csv'
data = [
    ['Name', 'Age', 'City'],
    ['Alice', '30', 'New York'],
    ['Bob', '25', 'Los Angeles'],
    ['Charlie', '35', 'Chicago']
]
write_csv(file_path, data)

使用字典读取 CSV 文件

import csv

def read_csv_as_dict(file_path):
    with open(file_path, mode='r', newline='', encoding='utf-8') as file:
        reader = csv.DictReader(file)
        for row in reader:
            print(row)

# 示例用法
file_path = 'example.csv'
read_csv_as_dict(file_path)

使用字典写入 CSV 文件

import csv

def write_csv_from_dict(file_path, fieldnames, data):
    with open(file_path, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(data)

# 示例用法
file_path = 'output.csv'
fieldnames = ['Name', 'Age', 'City']
data = [
    {'Name': 'Alice', 'Age': '30', 'City': 'New York'},
    {'Name': 'Bob', 'Age': '25', 'City': 'Los Angeles'},
    {'Name': 'Charlie', 'Age': '35', 'City': 'Chicago'}
]
write_csv_from_dict(file_path, fieldnames, data)

读取大文件时的优化

对于大文件,可以考虑逐行处理,以减少内存使用:

import csv

def read_large_csv(file_path):
    with open(file_path, mode='r', newline='', encoding='utf-8') as file:
        reader = csv.reader(file)
        for row in reader:
            # 处理每一行
            print(row)
            # 可以添加更多的处理逻辑

# 示例用法
file_path = 'large_example.csv'
read_large_csv(file_path)

处理包含空格或特殊字符的 CSV 文件

有时候 CSV 文件的字段值可能包含空格或特殊字符,这时候可以指定 csv 模块的参数,如 delimiterquotechar

import csv

def read_special_csv(file_path):
    with open(file_path, mode='r', newline='', encoding='utf-8') as file:
        reader = csv.reader(file, delimiter=';', quotechar='"')
        for row in reader:
            print(row)

# 示例用法
file_path = 'special_example.csv'
read_special_csv(file_path)

这些示例涵盖了大多数常见的 CSV 文件处理需求,根据具体的应用场景,可以灵活运用这些方法和参数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

杰哥在此

赠人玫瑰 手有余香

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

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

打赏作者

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

抵扣说明:

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

余额充值