python csv 简单操作
Posted xgege
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python csv 简单操作相关的知识,希望对你有一定的参考价值。
# -*- coding: utf-8 -*-
import csv
data1 = [[‘name‘, ‘age‘, ‘sex‘],
[‘张三‘, ‘19‘, ‘男‘],
[‘李四‘, ‘22‘, ‘男‘],
[‘王五‘, ‘20‘, ‘男‘],
[‘赵六‘, ‘18‘, ‘女‘]]
# writer
with open(‘csvFile1.csv‘, ‘w‘) as file:
# 解决中间有空行,也可以在open函数中加newline=‘‘解决
writer = csv.writer(file, lineterminator=‘
‘)
writer.writerows(data1)
# reader
with open(‘csvFile1.csv‘) as file:
reader = csv.reader(file)
for row in reader:
print(row)
# DicReader
data2 = []
with open(‘csvFile1.csv‘) as file:
dic_reader = csv.DictReader(file)
for row in dic_reader:
print(row)
data2.append(row)
# DicWriter
header_data = [‘name‘, ‘age‘, ‘sex‘]
with open(‘csvFile2.csv‘, ‘w‘, newline=‘‘) as file:
dic_writer = csv.DictWriter(file, fieldnames=header_data)
dic_writer.writeheader()
for row in data2:
dic_writer.writerow(row)
参考连接
以上是关于python csv 简单操作的主要内容,如果未能解决你的问题,请参考以下文章
python 用于在终端中运行的sublime text 3的简单代码片段制作工具