python2 中文乱码解决方法: https://www.cnblogs.com/phyger/p/9561283.html
使用pandas
import pandas a = { "姓名":['张三'], "年龄":[23] } data = pandas.DataFrame(a) # a需要是字典格式 # mode='a'表示追加, index=True表示给每行数据加索引序号, header=False表示不加标题 data.to_csv("test.csv",mode='a',index=True,header=False,)
import pandas a = ['张三',23] data = pandas.DataFrame(data=a) # # mode='a'表示追加, index=True表示给每行数据加索引序号, header=False表示不加标题 data.to_csv("test.csv",mode='a',index=True,header=['name', 'age'],)
原文链接:https://blog.csdn.net/weixin_38858749/article/details/117699357
csv操作
写入
# # w 为写 a 为追加 # # newline='': 这个限定插入新数据不会空行,如果没有这个,每次插入数据都会隔行填数据 # with open("test.csv","a",newline='') as csvfile: # writer = csv.writer(csvfile) # #先写入columns_name # writer.writerow(["index","a_name","b_name",'xx']) # #写入一行用writerow # writer.writerow([0,1,u"锴傧"]) # # 写入多行用writerows # writer.writerows([[11,11,31],[21,21,31],[31,31,41]])
追加
file=open("test.csv",'r',encoding='utf-8') userlines=file.readlines() # print (userlines) file.close() print (userlines) with open("test2.csv","w",newline='') as csvfile: writer = csv.writer(csvfile) #先写入columns_name writer.writerow(["index","a_name","b_name",'xx']) writer.writerow([0,1,2,u'zhuij'])
读取
# file=open("test.csv",'r',encoding='utf-8') # userlines=file.readlines() # # print (userlines) # file.close() # for line in userlines: # username=line.split(',')[0] #读取用户名 # dpassword2=line.split(',')[1] #读取密码 # password=line.split(',')[2] #读取密码 # print(password)
不使用with的写法
file=open("test2.csv","w",newline='')
writer = csv.writer(file)
#先写入columns_name
writer.writerow(["index","a_name","b_name",'xx'])
writer.writerow([0,1,2,u'zhuij'])
file.close()