CSV文件的读取:单个读取和批量读取
import numpy as np
import csv
#单个文件
#读取CSV文件
with open(r'D:\JupyterCode\abcdefg.csv') as csvfile: #读取csv文件
#with open('E:/UQ/Abaqus+python/case/KL_right/infer_lamda.csv') as csvfile:
spamreader = csv.reader(csvfile)
data_x = [] # 定义一个空数组用于保存文件的数据
for item in (spamreader):
#print(item)
data_x.append(item)
#(1) 读取CSV的全部内容
data_x[i] = [[float(x) for x in row] for row in data_x] # 将数据从string形式转换为float形式
data_x = np.array(data_x) # 将list数组转化成array数组便于查看数据结构
#ps:用 pd.read_csv(r'path/xx.csv',header=None) 读取比上面with open as csvfile的方法更快
#(2) 读取CSV的部分内容,如100项之后的内容
for i in range (100,len(item)):
data_x[i] = [[float(x) for x in row] for row in data_x]
data_x = np.array(data_x)
#批量读取CSV文件
num=8 #设置有8个文件,同时也是文件名
res=[] #用于合并
for i in range(num):
with open(r'C:\Users\Administrator\Desktop\计算结果\CSV_R%d.csv'%(i+1)) as csvfile:
spamreader = csv.reader(csvfile)
data_x = []
for item in (spamreader):
data_x.append(item)
data_x = [[float(x) for x in row] for row in data_x]
data=np.array(data_x)
restt=np.vstack((data[:,0],data[:,1])) #合并CSV文件中的第一列和第二列
res.append(restt) #合并所有CSV文件 最后输出res
CSV文件的输出:
#输出CSV文件
f = open('output.csv','w',encoding='utf-8')
#如果输出的CSV文件中有空白行,则补充:newline='')
csv_writer = csv.writer(f)
for i in range(len(data_x):
csv_writer.writerow(data_x[i])
f.close()
print('finished')