import csv
import pandas as pd
import numpy as np
a = np.array([[1,2,3,4,5,6],
[4,5,6,3,2,2],
[5,6,5,6,3,9]])
csv_path = "test.csv"
def write_csv(csv_path, M):
with open(csv_path, 'w', encoding='utf-8', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerows(M)
def ite_write_csv(csv_path, row):
'''
追加写入,每次只写入一行
'''
with open(csv_path, 'a+', newline='', encoding='utf-8') as csvfile:
csv_write = csv.writer(csvfile)
csv_write.writerow(row)
def read_csv(csv_path):
'''
一次性读出整个文件中的内容
'''
M = pd.read_csv(csv_path, encoding='utf-8', header=None)
M.values.astype('float64')
return M
def ite_read_csv(csv_path):
'''
返回一个迭代器,适用于csv文件太大,不能一次性读出所有的数据
'''
datafile = open(csv_path, encoding='utf-8') # 读取预处理结果
csv_reader = csv.reader(datafile)
return csv_reader
write_csv(csv_path, a)
b = read_csv(csv_path)
csv_reader = ite_read_csv(csv_path)
for row in csv_reader:
print(np.array(row).astype('float64'))
c = np.array(row).astype('float64')
ite_write_csv("test2.csv", c)
# 注意迭代器中的元素是list类型,需要先转成array;
# 此外row中的元素是字符类型,需要用astype转类型
Python 将矩阵存为csv文件以读取csv文件
最新推荐文章于 2024-07-05 03:29:43 发布