1. txt
1.1 写入 txt 文件
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()
2. csv
2.1. 写入csv文件
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()
2.2 读csv
我的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']) # 按照字典关键字读取相应位置的数据
输出的部分结果: