# save numpy as csv
import numpy as np
np.savetxt('frame',array,fmt='%d',delimiter=None) #frame: 文件 array:存入文件的数组
# fmt:写入文件的格式,如%d %f %e delimiter:分割字符串,默认空格
#load csv
np.loadtxt('frame',dtype=np.int,delimiter=None,unpack=False) # frame:文件
# dtype:数据类型 delimiter:分割字符串 unpack:若为True,则读入属性奖分别写入不同变量
import pandas as pd
# 任意的多组列表
a = [1, 2, 3]
b = [4, 5, 6]
# 字典中的key值即为csv中列名
dataframe = pd.DataFrame({'a_name': a, 'b_name': b})
# 将DataFrame存储为csv,index表示是否显示行名,default=True
dataframe.to_csv("test.csv", index=False, sep=',')
# load csv
import pandas as pd
data = pd.read_csv('test.csv')
# save csv
import csv
# python2可以用file替代open
with open("test.csv", "w") as csvfile:
writer = csv.writer(csvfile)
# 先写入columns_name
writer.writerow(["index", "a_name", "b_name"])
# 写入多行用writerows
writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])
# save csv
import csv
# 1. 创建文件对象
f = open('文件名.csv','w',encoding='utf-8')
# 2. 基于文件对象构建 csv写入对象
csv_writer = csv.writer(f)
# 3. 构建列表头
csv_writer.writerow(["姓名","年龄","性别"])
# 4. 写入csv文件内容
csv_writer.writerow(["l",'18','男'])
csv_writer.writerow(["c",'20','男'])
csv_writer.writerow(["w",'22','女'])
# 5. 关闭文件
f.close()
# load csv
import csv
with open("test.csv","r") as csvfile:
reader = csv.reader(csvfile)
#这里不需要readlines
for line in reader:
print line
csv读取保存
csv读取保存