首页 > 解决方案 > 在 Python 3 中写入同一行的文件

问题描述

我正在尝试使用以下五行代码在文本文件中的单词末尾添加“123”和“12345”,但我遇到了一些问题。

我做了一些研究,并通过使用取得了一些进展file.write(str(x+y)),但是这个网站上的其他问题经常涉及\n,我没有使用。

我该如何解决?

代码

file = open("test.txt", "r+")
add = ['123', '12345']
for x in file:
  for y in add:
    file.write(str(x+y))

输出

test (ORIGINAL WORD THAT ALREADY EXISTED IN THE TEXT FILE)
test
123test
12345

期望的输出

test (ORIGINAL WORD THAT ALREADY EXISTED IN THE TEXT FILE)
test123
test12345

标签: python-3.xlist

解决方案


我认为问题可能来自使用“r+”参数进行写入。更安全的方法是将读取和写入操作拆分为两个单独的调用。

with open("test.txt", "r+") as file:
    t = file.read()
with open("test.txt", "a+") as file:
    for y in add:
        file.write("\r\n" + t + y)

推荐阅读