首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将python写入文件并不像预期的那样写入。

将python写入文件并不像预期的那样写入。
EN

Stack Overflow用户
提问于 2022-09-19 16:07:48
回答 1查看 28关注 0票数 0

好的,我试图写到python中的一个文件,我有一个for循环来查找文本文件中的特定行,然后更新该列表中的行,但是当我将行写到新的文本文件时,它们都写在一行中。这是我的代码:

代码语言:javascript
复制
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_

实际结果:

代码语言:javascript
复制
1 P acf/_ott_phi_sec_into_future P acf/_ott_roll_response P acf/_ott_phi_deg_off_for_full_def
EN

回答 1

Stack Overflow用户

发布于 2022-09-19 16:16:17

您可能希望添加\n以从新行开始。

代码语言:javascript
复制
APfile.write('\n'.join(APlist))

编辑:你可能想要删除内容,然后写你的列表。因此,您需要交换、编写和截断。

代码语言:javascript
复制
APfile.seek(0)
APfile.truncate()
APfile.write('\n'.join(APlist))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73776306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档