import os
# 文件地址
txt_path = r'../data/train_256_64_0.txt'
# 打开文件
file = open(txt_path, 'w', encoding='utf-8')
# 写入
file.write(name + '\n')
file.write('内容' + '\n')
········
# 关闭文件
file.close()
import csv
# 写入的文件地址
log_path = r'C:\Users\DELL\Desktop\test\size.csv'
file = open(log_path, 'a+', encoding='utf-8', newline='')
csv_writer = csv.writer(file)
# 写表头
csv_writer.writerow([f'name', 'white proportion']) # []内是表头名,可根据自己的数量情况进行更换
# 写内容
csv_writer.writerow([name, white_proportion])
csv_writer.writerow([name, white_proportion])
······
# 关闭文件
file.close()
参考链接:教你用Python读取CSV文件的5种方式
我的csv文件:
import csv
csv_path = 'csv文件地址'
with open(csv_path) as f:
f_csv = csv.DictReader(f)
for row in f_csv:
print(row) # 读取一行,不包括表头
print('Acc: ', row['Acc']) # 按照字典关键字读取相应位置的数据
输出的部分结果: