python-3.x - 在 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
解决方案
我认为问题可能来自使用“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)
推荐阅读
- command-line - 命令提示符打开到 L:\
- c - 使用 C 预处理器进行“可变”长度初始化
- c# - F12 键在 asp.net Visual Studio 2019 中不起作用
- reactjs - react中的jspsych图片实验
- css - 使用 CSS @page :first 更改打印边距会导致其他页面截断文本
- java - java system.out.println 打印字节时
- shopify-app - 有没有办法从我的 Shopify 应用程序捕获在 Shopify 网站前端发出的特定请求?
- verilog - $readmemh 不从数据文件中读取值
- python - 关于 hive python 的角度
- javascript - :hover 覆盖 :active 样式 - CSS