# -*- coding: utf-8 -*-
import csv
def one1():
#第一种方式读取含第一行所有的csv文件,默认按每行列表形式输出
with open("test2.csv", "r", encoding="gbk") as f:
reader = csv.reader(f)
for i in reader:
print(i)
def one2():
# 指定哪一行不输出,其它默认按列表一行一行的输出
with open("test2.csv", "r", encoding="gbk") as f:
reader = csv.reader(f)
#一个next跳过一行
next(reader)
for i in reader:
print(i)
def one3():
#取其中列,每列一行按字典格式输出
with open("test2.csv", "r", encoding="gbk") as f:
reader = csv.reader(f)
#用dictreader不会包含第一行标题
reader = csv.DictReader(f)
for i in reader:
value = {"服务器正面要贴的标签":i['服务器正面要贴的标签'], "交换机网线上面的头要贴的标签":i['交换机网线上面的头要贴的标签']}
print(value)
def one4():
#写入csv文件
header = ["username", "age", "height"]
# 要写入的文件为元组类型
values = [('张三',21, 180), ('李四',27, 180), ('小猎',22, 180)]
# newline解决默认\n问题,这样就没有换行了
with open("write_csv.csv", 'w', encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(values)
def one5():
# 这样写入csv文件
header = ["username", "age", "height"]
# 要写入的文件为字典类型
values = [
{'username': '张三', 'age': 23, 'height': 180},
{'username':'李四', 'age': 22, 'height': 180},
{'username':'小猎', 'age': 21, 'height': 180}
]
# newline解决默认\n问题,这样就没有换行了
with open("write_csv.csv", 'w', encoding="utf-8", newline="") as f:
#这里直接写入头一行标题
writer = csv.DictWriter(f, header)
writer.writeheader()
writer.writerows(values)
if __name__ == '__main__':
one5()
python csv各种案例
最新推荐文章于 2021-05-07 18:57:38 发布