gpt4 book ai didi

python用seek替换fileinput

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

我有一个以 </END> 结尾的文件文件可能在 </END> 之后包含空行。 。我不关心空行。但最后一个非空白单词是 </END> 。我需要在 </END> 之前添加几行。我已经用 fileinput 完成了此操作

for each_line in fileinput.input("testme",inplace=True):
if each_line.strip() == '</END>':
print "\nAdding ^.*"+source_resource+".*$ \\"
print destination+" [R="+http_code+",L]"
print each_line,

请一些专家告诉我如何通过 seek 来实现这一点。我相信seek对于光标定位非常方便。

最佳答案

您有两种可能的方法,一种使用就地写入,另一种意味着创建文件的副本。

第二种方法非常容易实现:

with open(src_path, "r") as in_f, open(dest_path, "w") as out_f:
for line in in_f:
if line == "</END>":
out_f.write("whatever you want")
out_f.write(line)
out_f.write('\n')

对于第一种方法,我们需要检测结束线并移回其开头:

last = 0
with open(src_path, "r+") as f:
for line in f:
if line == "</END>":
f.seek(last)
f.write("whatever you want"
f.write(line) # rewrite the line
f.write('\n')
last = f.tell() # This will give us the end of the last line

这段代码是我用脑子写的,所以可能会有一些错误,但你明白了。

关于python用seek替换fileinput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17063872/

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