好的,我试图写到python中的一个文件,我有一个for循环来查找文本文件中的特定行,然后更新该列表中的行,但是当我将行写到新的文本文件时,它们都写在一行中。这是我的代码:
APfile = open(r"C:\X-Plane 11\Aircraft\Perlan2\Perlan2.acf", "r+")
APlist = APfile.readlines()
line_index = []
# iterates through each line of file to find specific string value apends line number to line_index list
for line in APlist:
if line.find('P acf/_ott_phi_sec_into_future') != -1:
line_index.append(APlist.index(line)-1)
# pred_index = APlist.index(line)
if line.find('P acf/_ott_roll_response') != -1:
line_index.append(APlist.index(line)-1)
if line.find('P acf/_ott_phi_deg_off_for_full_def') != -1:
line_index.append(APlist.index(line)-1)
if line.find('P acf/_ott_roll_rate') != -1:
line_index.append(APlist.index(line)-1)
if line.find('P acf/_ott_phi_sec_to_tune') != -1:
line_index.append(APlist.index(line)-1)
# takes line index to map function inputs as new autopilot constant values
APlist[line_index[0]] = "P acf/_ott_phi_sec_into_future" ' ' + roll_pred
APlist[line_index[1]] = "P acf/_ott_roll_response" + ' ' + roll_resp
APlist[line_index[2]] = "P acf/_ott_phi_deg_off_for_full_def" + ' ' + roll_error
APlist[line_index[3]] = "P acf/_ott_roll_rate" + ' ' + roll_rate
APlist[line_index[4]] = "P acf/_ott_phi_sec_to_tune" + ' ' + roll_tunetime
APfile.seek(0)
APfile.writelines(APlist)
APfile.truncate()
#closes file
APfile.close()预期结果:
1P acf/_ott_phi_sec_
2 P acf/ott滚动响应
3P acf/_ott_phi_deg_
实际结果:
1 P acf/_ott_phi_sec_into_future P acf/_ott_roll_response P acf/_ott_phi_deg_off_for_full_def发布于 2022-09-19 16:16:17
您可能希望添加\n以从新行开始。
APfile.write('\n'.join(APlist))编辑:你可能想要删除内容,然后写你的列表。因此,您需要交换、编写和截断。
APfile.seek(0)
APfile.truncate()
APfile.write('\n'.join(APlist))https://stackoverflow.com/questions/73776306
复制相似问题