答案:Python通过csv模块读写CSV文件,需注意编码、分隔符和引号处理;读取时用csv.reader配合with open确保文件正确关闭,指定encoding避免乱码;写入时使用csv.writer并设置newline=''防止空行;处理特殊字符可配置delimiter、quotechar和quoting参数;对于大文件,可采用逐行迭代或pandas分块读取chunksize来降低内存消耗。

Python读写CSV文件,简单来说,就是利用
csv
Python通过内置的
csv
1. 读取CSV文件:
import csv
def read_csv_file(filename):
"""读取CSV文件并返回数据列表。"""
data = []
try:
with open(filename, 'r', encoding='utf-8') as csvfile:
csv_reader = csv.reader(csvfile)
header = next(csv_reader) # 跳过标题行,如果存在的话
for row in csv_reader:
data.append(row)
except FileNotFoundError:
print(f"文件未找到: {filename}")
except Exception as e:
print(f"读取文件时发生错误: {e}")
return data
# 示例用法
csv_data = read_csv_file('example.csv')
if csv_data:
for row in csv_data:
print(row)
这里用了
with open()
encoding='utf-8'
csv.reader
next(csv_reader)
立即学习“Python免费学习笔记(深入)”;
2. 写入CSV文件:
import csv
def write_csv_file(filename, data, header=None):
"""将数据写入CSV文件。"""
try:
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
csv_writer = csv.writer(csvfile)
if header:
csv_writer.writerow(header) # 写入标题行
csv_writer.writerows(data) # 写入数据行
except Exception as e:
print(f"写入文件时发生错误: {e}")
# 示例用法
data_to_write = [
['Alice', 25, 'Engineer'],
['Bob', 30, 'Doctor'],
['Charlie', 22, 'Student']
]
header = ['Name', 'Age', 'Occupation'] # 可选
write_csv_file('output.csv', data_to_write, header)'w'
newline=''
csv.writer
writerow
writerows
CSV文件里经常会有逗号、引号之类的特殊字符,这些字符如果处理不好,会导致数据解析错误。
csv
quoting
quotechar
quoting
csv.QUOTE_MINIMAL
csv.QUOTE_ALL
csv.QUOTE_NONNUMERIC
csv.QUOTE_NONE
csv.Error
quotechar
"
例如,如果你的CSV文件使用竖线
|
'
import csv
def read_csv_with_custom_delimiter(filename):
"""使用自定义分隔符和引号读取CSV文件。"""
data = []
try:
with open(filename, 'r', encoding='utf-8') as csvfile:
csv_reader = csv.reader(csvfile, delimiter='|', quotechar="'")
for row in csv_reader:
data.append(row)
except FileNotFoundError:
print(f"文件未找到: {filename}")
except Exception as e:
print(f"读取文件时发生错误: {e}")
return data
# 示例用法
custom_csv_data = read_csv_with_custom_delimiter('custom.csv')
if custom_csv_data:
for row in custom_csv_data:
print(row)
写入的时候也类似,只需要在
csv.writer
delimiter
quotechar
quoting
如果CSV文件非常大,一次性读取到内存可能会导致内存溢出。这时候,可以使用迭代器逐行读取,或者使用
pandas
1. 使用迭代器:
csv.reader
import csv
def process_large_csv(filename):
"""逐行处理大型CSV文件。"""
try:
with open(filename, 'r', encoding='utf-8') as csvfile:
csv_reader = csv.reader(csvfile)
header = next(csv_reader) # 跳过标题行
for row in csv_reader:
# 在这里处理每一行数据
process_row(row)
except FileNotFoundError:
print(f"文件未找到: {filename}")
except Exception as e:
print(f"读取文件时发生错误: {e}")
def process_row(row):
"""处理单行数据的函数。"""
# 例如,打印第一列数据
print(row[0])
# 示例用法
process_large_csv('large.csv')2. 使用pandas
pandas
read_csv
chunksize
import pandas as pd
def process_large_csv_with_pandas(filename, chunksize=1000):
"""使用pandas分块读取大型CSV文件。"""
try:
for chunk in pd.read_csv(filename, chunksize=chunksize):
# 在这里处理每个数据块
process_chunk(chunk)
except FileNotFoundError:
print(f"文件未找到: {filename}")
except Exception as e:
print(f"读取文件时发生错误: {e}")
def process_chunk(chunk):
"""处理数据块的函数。"""
# 例如,打印每个数据块的行数
print(len(chunk))
# 示例用法
process_large_csv_with_pandas('large.csv', chunksize=10000)pandas
read_csv
chunksize
编码问题是CSV文件读写中常见的坑。如果CSV文件使用了非UTF-8编码,读取时可能会出现乱码。为了避免这个问题,应该始终指定正确的编码方式。
读取文件时,指定encoding
with open(filename, 'r', encoding='gbk') as csvfile: # 例如,使用GBK编码
csv_reader = csv.reader(csvfile)
# ...常用的编码方式有
utf-8
gbk
gb2312
latin1
chardet
写入文件时,同样指定encoding
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
csv_writer = csv.writer(csvfile)
# ...保持读取和写入的编码方式一致,可以避免乱码问题。
总的来说,Python读写CSV文件并不难,但需要注意细节,尤其是处理特殊字符和编码问题。使用
csv
pandas
以上就是python如何读取和写入csv文件_python CSV文件读写操作指南的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号