情況:有一份文檔需要將其中252個不同值的"sza=“替換為另外一組數據?;
其中,替換參數值.txt 的格式就是把要替換的數據粘貼到 txt中,成一列就可以了;
PS:要是想改文本文檔里的其他參數,把代碼中的"sza”換成要改的參數名稱就行了。
# 讀取txt文件中的sza值
sza_list = []
with open(r'D:\Users\DELL\Desktop\替換參數值.txt', 'r') as file:for line in file:sza_value = float(line.strip())sza_list.append(sza_value)# 讀取文件內容
with open(r'D:\Users\DELL\Desktop\替換文本文檔.txt', 'r') as file:data = file.readlines()# 處理所有的SZA值
sza_index = 0
for index, line in enumerate(data):if 'sza=' in line:new_sza = sza_list[sza_index]data[index] = f' sza={new_sza:.2f} !solar zenith angle (not used if zero)\n'sza_index += 1# 寫入修改后的內容
with open(r'D:\Users\DELL\Desktop\替換完成文檔.txt', 'w') as file:file.writelines(data)