gpt4 book ai didi

python - 在 python 3.1 中编辑单个 .txt 行

转载 作者:行者123 更新时间:2023-11-28 19:45:57 25 4
gpt4 key购买 nike

我有一些数据以这种格式存储在 .txt 文件中:

----------|||||||||||||||||||||||||-----------|||||||||||
1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943
1020414646canBeFollowedBySpaces 3292532113435532419963

不要问...

我有很多行,我需要一种方法来在特定行的末尾添加更多数字。

我已经编写了代码来查找我想要的行,但我对如何在它的末尾添加 11 个字符感到困惑。我环顾四周,这个网站对我遇到的其他一些问题很有帮助,但我似乎找不到我需要的东西。

保持该行在文件中的位置及其当前顺序的内容很重要。

使用 python3.1,你将如何转换它:

1020414646canBeFollowedBySpaces    3292532113435532419963

进入

1020414646canBeFollowedBySpaces    329253211343553241996301846372998

最佳答案

作为一般原则,在文本文件中“插入”新数据没有捷径可走。您需要在新文件中复制整个原始文件,同时修改您想要的文本行。

例如:

with open("input.txt") as infile:
with open("output.txt", "w") as outfile:
for s in infile:
s = s.rstrip() # remove trailing newline
if "target" in s:
s += "0123456789"
print(s, file=outfile)
os.rename("input.txt", "input.txt.original")
os.rename("output.txt", "input.txt")

关于python - 在 python 3.1 中编辑单个 .txt 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5048217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com