python用pandas读写和追加csv文件

Tia ·
更新时间:2024-09-20
· 228 次阅读

目录

csv文件

一、创建csv文件

二、读写csv文件

1.基础python

2.pandas

三、追加csv文件

1.基础python

2.pandas

总结

csv文件

CSV文件是最常用的一个文件存储方式。逗号分隔值(Common-Separated Values,CSV)文件以纯文本形式存储表格数据(注:分隔字符也可以是其他字符)。纯文本说明该文件是一个字符序列,不包含必须像二进制数字那样被解读的数据。

CSV文件由任意数目记录组成,记录间以某种换行符分隔;每条记录由若干字段组成,字段间以字符(如逗号)或字符串分隔。

一、创建csv文件

用记事本打开如图所示

二、读写csv文件 1.基础python import csv with open('supplier_data.csv','r')as f: reader = csv.reader(f) for row in reader: print(row)

2.pandas import pandas as pd df = pd.read_csv('supplier_data.csv') print(df)

三、追加csv文件 1.基础python import csv with open('supplier_data.csv','a') as f: writer = csv.writer(f) writer.writerow(['7','hu','18','100','90','85']) writer.writerow(['8','zahng','19','87','97','77'])

此时我们发现加入的数据会空一行,要解决这个问题我们要用到newline=‘’

import csv with open('supplier_data.csv','a',newline='') as f: writer = csv.writer(f) writer.writerow(['7','hu','18','100','90','85']) writer.writerow(['8','zahng','19','87','97','77'])

此时,上述代码出现的问题就解决了

2.pandas import pandas a={'sid':[7],'sname':['hu'],'sage':[18],'math':[100],'english':[90],'cs':[85]} df = pandas.DataFrame(a) #mode = 'a'为追加数据,index为每行的索引序号,header为标题 df.to_csv('supplier_data.csv',mode='a',index=False,header=False) 总结

到此这篇关于python用pandas读写和追加csv文件的文章就介绍到这了,更多相关python pandas操作csv文件内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



csv文件 pandas csv Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号