gpt4 book ai didi

python - 读取文件并写入我刚刚读取的行

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:54 25 4
gpt4 key购买 nike

所以我想通读一个文件,检查每一行,看看它是否包含我正在查找的字符串的一部分。一旦找到正确的行,我就想在文件中重写该行。

这是我到目前为止所拥有的:

f = open("playlist.py", "r+")
for line in f:
if old in line:
f.write(" " + str(item) + ":" + " " +
"\"" + new_text + "\"")
f.close()
break
f.close()

此代码正在查找正确的行,但写入文件末尾。我有点认为读写迭代器会被共享,但我想不是:(

最佳答案

使用文件输入

import fileinput

for line in fileinput.input("test.txt", inplace=True):
if contains_str_youlookingfor:
print "what_you_want_to_rewire"
else:
print line.rstrip()
fileinput.close()

如果您使用的是 Python 3.2+,则首选上下文管理器:

with fileinput.input("test.txt", inplace=True) as f:    
for line in f:
if contains_str_youlookingfor:
print("what_you_want_to_rewire")
else:
print(line, end='')

这些行将被替换为“what_you_want_to_rewire”,并且不会创建新文件。

编辑
如果您不删除原始换行符或在没有换行符的情况下进行打印,那么您将得到额外的空行。

关于python - 读取文件并写入我刚刚读取的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22874858/

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