在跑实验时遇到一个小问题,需要对文本数据(.dat文件)中的内容批量做修改,每个目录下大约有1000条,尝试用python写个脚本去处理
NumDevices = 8;
NumSlotes = 64;
GivenBandwidthOld = [0.152539, 0.0675514, 0.0755368, 0.0871062, 0.133525, 0.0969185, 0.148601, 0.0748586];
GivenLatency = [9.56362, 16.5431, 18.4332, 14.8242, 12.2099, 16.2364, 7.78907, 15.705];
HighestPossibleCritFunctionValue = 1.1;
需要对第一行,第三行和第四行做修改,参数NumDevices
需要分别改为2,3,4,5,6,7,则下面的两个列表中的数据数量需要与之对应
NumDevices = 2
为例NumDevices = 2;
NumSlotes = 64;
GivenBandwidthOld = [0.152539, 0.0675514];
GivenLatency = [9.56362, 16.5431];
HighestPossibleCritFunctionValue = 1.1;
import os
import glob
if __name__ == '__main__':
txt_list = glob.glob("E:/Code/Pycharm workplace/TDM-script/801-1000/*.dat")
#依次读取目录下的每个文件
for txt_item in txt_list:
with open(txt_item) as f:
lines = f.readlines()
with open(txt_item, 'w') as f:
#对每个文件,读取每一行并按关键字判断是否需要修改
for line in lines:
s1 = 'NumDevices'
s2 = 'GivenBandwidthOld'
s3 = 'GivenLatency'
if s1 in line:
line_split_1 = line.strip().split()
new1 = line_split_1[0] + ' ' + line_split_1[1] + ' ' + '2;' + '\n'
f.write(new1)
elif s2 in line:
line_split_2 = line.strip().split()
new2 = line_split_2[0] + ' ' + line_split_2[1] + ' ' + line_split_2[2] + ' ' + line_split_2[3] + ']' + '\n'
f.write(new2)
elif s3 in line:
line_split_3 = line.strip().split()
new3 = line_split_3[0] + ' ' + line_split_3[1] + ' ' + line_split_3[2] + ' ' + line_split_3[3] + ']' + '\n'
f.write(new3)
else:
f.write(line)