Python CSV Reader/Writer
一、 基础背景:
Python 天生支持读取CSV 格式数据并且是可配置的。
- 在 Python 里边有个模块 csv ,
- 它包含了CSV 读取/生成所需的所有支持,并且它遵守 RFC标准(除非你覆盖了相应的配置),
- 因此默认情况下它是能够读取和生成合法的 CSV 文件。
二、使用介绍
1、导入模块
import csv
2、Python CSV 方法
方法 | 描述 |
---|---|
csv.reader | 返回一个遍历 CSV 文件各行的读取器对象 |
csv.writer | 返回将数据写入 CSV 文件的写入器对象 |
三、Demo代码
- Demo代码其实很简单,就是读取和写入Excel数据。
1、读csv:
import csv
with open('test1.csv', 'r') as csv_file:
reader = csv.reader(csv_file)
for row in reader:
print(str(row))
- 代码中我们导入了 csv 模块并且打开了 “test1.csv” 文件,将文件作为参数传给
csv.reader,调用这个方法后我们将reader 里边的每行数据输出。
假设 ‘test1.csv’ 里边的内容为:
1. ['my first column', 'my second column', 'my third column']
2. ['my first column 2', 'my second column 2', 'my third column 2']
那么我们运行这个代码后,相应的输出:
['my first column', 'my second column', 'my third column']
['my first column 2', 'my second column 2', 'my third column 2']
2、写入csv
csv.writer()
方法返回一个 writer 对象,该对象将用户数据转换为给定文件对象上的定界字符串。writerow()
将一个列表全部写入csv的同一行。writerows()
方法将所有给定的行写入csv 文件。
生成和读取一样的简单
import csv
rows = [['1', '2', '3'], ['4', '5', '6']]
csv_file=open('my.csv', 'w', newline='')
with csv_file:
writer = csv.writer(csv_file)
for row in rows:
writer.writerow(row)
在my.csv 文件的数据会是:
1,2,3
4,5,6
输出的内容:
['1', '2', '3']
['4', '5', '6']
- 到这里我们都非常清楚代码逻辑。我们将文件作为参数给 writer,以写模式打开,然后用它来写每一行数据。
四、注意点:
writerow()
writerow()将一个列表全部写入csv的同一行。
import csv
csv_list = ['a','b','c','d']
csvfile=open('D:/AllKindsOfWords/test/test.csv', 'w',newline = '')
writer = csv.writer(csvfile)
writer.writerow(csv_list)
结果:
writerows()
writerows()将一个二维列表中的每一个列表写为一行。
import csv
csv_list = ['a','b','c','d']
csvfile=open('D:/AllKindsOfWords/test/test.csv', 'w',newline = '')
writer = csv.writer(csvfile)
writer.writerows(csv_list)
结果: