Python CSV模块
a.CSV介绍
1、csv简介
CSV (Comma Separated Values),即逗号分隔值(也称字符分隔值,因为分隔符可以不是逗号),是一种常用的文本.
CSV是一种以逗号分隔数值的文件类型,在数据库或电子表格中,常见的导入导出文件格式就是CSV格式,CSV格式存储数据通常以纯文本的方式存数数据表。
格式,用以存储表格数据,包括数字或者字符。很多程序在处理数据时都会碰到csv这种格式的文件,它的使用是比
较广泛的(Kaggle上一些题目提供的数据就是csv格式),csv虽然使用广泛,但却没有通用的标准,所以在处理csv
格式时常常会碰到麻烦,幸好python内置了csv模块。下面简单介绍csv模块中最常用的一些函数。
a.写入CSV
1.写入列表List
import csv
if __name__ == '__main__':
headers = ['class', 'name', 'sex', 'height', 'year']
rows = [
[1, 'xiaoming', 'male', 168, 23],
[1, 'xiaohong', 'female', 162, 22],
[2, 'xiaozhang', 'female', 163, 21],
[2, 'xiaoli', 'male', 158, 21]
]
with open('./files/test1.csv', 'w', newline='')as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
import csv
with open("D:\\test.csv",'a') as f:
row=['曹操','23','学生','黑龙江','5000']
write=csv.writer(f)
write.writerow(row)
print("写入完毕!")
2.写入字典Dict
参考help(csv.DictWriter)可知,在写入字典序列类型数据的时候,需要传入两个参数,一个是文件对象——f,一个是字段名称——fieldnames,到时候要写入表头的时候,只需要调用writerheader方法,写入一行字典系列数据调用writerow方法,并传入相应字典参数,写入多行调用writerows
具体代码如下:
import csv
if __name__ == '__main__':
headers = ['class', 'name', 'sex', 'height', 'year']
rows = [
{'class': 1, 'name': 'xiaoming', 'sex': 'male', 'height': 168, 'year': 23},
{'class': 1, 'name': 'xiaohong', 'sex': 'female', 'height': 162, 'year': 22},
{'class': 2, 'name': 'xiaozhang', 'sex': 'female', 'height': 163, 'year': 21},
{'class': 2, 'name': 'xiaoli', 'sex': 'male', 'height': 158, 'year': 21},
]
with open('./files/test2.csv', 'w', newline='')as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
b.读取CSV
读取表头
import csv
with open("D:\\test.csv") as f:
reader = csv.reader(f)
rows=[row for row in reader]
print(rows[0])
02.读取excel文件数据
import pandas as pd
data = pd.read_excel(filepath)
拷贝内容
import pandas as pd
file=open('test.csv')
data=pd.read_csv(file)
data.to_csv('Aim.csv')
print(data)
参考文章
Original: https://blog.csdn.net/weixin_45750972/article/details/122276219
Author: Harris-H
Title: Python CSV模块
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/697784/
转载文章受原作者版权保护。转载请注明原作者出处!