import csv
# 源文件名
filename = "./test1.csv"
pf_file = "./test1.pf"
singular_line = [] # 单数行
double_line = [] # 双数行
num_obj = 10 # 目标个数,这表示其中列的个数
singular_data = [[] for i in range(num_obj)] # 单数行保存为一个num_obj列的二维数组
double_data = [[] for i in range(num_obj)] # 单数行保存为一个num_obj列的二维数组
# 将文件中的信息保存到singular_data和double_data这两个列表中
with open(filename, 'r', encoding='utf-8') as f:
i = 1
for line in f.readlines():
if i % 2 == 0:
double_line.append(line)
else:
singular_line.append(line)
i = i + 1
f.close()
# 再将两个列表中的数据进行处理,将双数行中的数据换顺序保存
# 单数行直接保存
for Sum in singular_line:
# print(Sum.split("\n")[0].split(",")[0:])
sum_eva_index = Sum.split("\n")[0].split(",")[0:]
for i in range(num_obj):
# print(sum_eva_index[i]) # test
singular_data[i].append(float(sum_eva_index[i]))
# 双数行反向后保存
for Sum in double_line:
sum_eva_index = Sum.split("\n")[0].split(",")[0:]
for i in range(num_obj):
# print("i", i)
double_data[i].append(float(sum_eva_index[num_obj - i - 1])) # 注意,即使num_obj是目标数量,但是索引是从num_obj-1开始的
# 将数据写入CSV文件中
# 将数据写入csv日志文件中
with open(pf_file, 'w') as f:
for i in range(len(singular_data[0])): # 3504
for j in range(len(singular_data)): # 10
# f.write([singular_data[0][i], singular_data[1][i], singular_data[2][i], singular_data[3][i],
# singular_data[4][i], singular_data[5][i], singular_data[6][i], singular_data[7][i],
# singular_data[8][i], singular_data[9][i]])
f.write(str(singular_data[j][i]))
# 用制表符做分割
if j!=(len(singular_data)-1):
f.write("\t")
# 换行符
f.write("\n")
for i in range(len(double_data[0])): # 3504
for j in range(len(double_data)): # 10
f.write(str(double_data[j][i]))
# 用制表符做分割
if j!=(len(double_data)-1):
f.write("\t")
# 换行符
f.write("\n")
f.close()
# with open(pf_file, "w", newline='') as f:
# writer = csv.writer(f)
#
# # print(len(singular_data)) # 10
# # print(len(singular_data[0])) # 3504
# # 遍历行
# for i in range(len(singular_data[0])): # i 取(0,1,2...)
# writer.writerow([singular_data[0][i], singular_data[1][i], singular_data[2][i], singular_data[3][i],
# singular_data[4][i], singular_data[5][i], singular_data[6][i], singular_data[7][i],
# singular_data[8][i], singular_data[9][i]])
#
# # 再写双数行
# for i in range(len(double_data[0])): # i 取(0,1,2...)
# writer.writerow([double_data[0][i], double_data[1][i], double_data[2][i], double_data[3][i],
# double_data[4][i], double_data[5][i], double_data[6][i], double_data[7][i],
# double_data[8][i], double_data[9][i]])
#
# f.close()