使用 Python 在特定文本之后将文本插入到文本文件中 [英] Insert text into a text file following specific text using Python

查看:39
本文介绍了使用 Python 在特定文本之后将文本插入到文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编辑一些文本文件以包含新信息,但我需要根据周围的文本在文件中的特定位置插入该信息.

这不符合我的需要:

 with open(full_filename, "r+") as f:行 = f.readlines()对于线中线:如果识别文本"在一行中:偏移量 = f.tell()f.seek(偏移)f.write('插入的文本')

...因为它将文本添加到文件的末尾.我如何将它写到识别文本之后的下一行?

(AFAICT,这不是类似问题的重复,因为没有人能够提供这个答案)

解决方案

如果你不需要就地工作,那么可能是这样的:

 with open("old.txt") as f_old, open("new.txt", "w") as f_new:对于 f_old 中的行:f_new.write(line)如果标识符"在线:f_new.write("额外的东西\n")

(或者,兼容 Python-2.5):

f_old = open("old.txt")f_new = open("new.txt", "w")对于 f_old 中的行:f_new.write(line)如果标识符"在线:f_new.write("额外的东西\n")f_old.close()f_new.close()

哪个转弯

<预><代码>>>>!cat old.txt一种乙Cd 标识符电子

进入

<预><代码>>>>!cat new.txt一种乙Cd 标识符额外的东西电子

(关于在 'string2' 中使用 'string1' 的常见警告:'enamel' 中的 'name' 为 True,'Othello' 中的 'hello' 为 True,等等,但显然您可以使条件任意复杂.)

I have to edit some text files to include new information, but I will need to insert that information at specific locations in the file based on the surrounding text.

This doesn't work the way I need it to:

 with open(full_filename, "r+") as f:
        lines = f.readlines() 
        for line in lines:
            if 'identifying text' in line:   
                offset = f.tell()
                f.seek(offset)  
                f.write('Inserted text')

...in that it adds the text to the end of the file. How would I write it to the next line following the identifying text?

(AFAICT, this is not a duplicate of similar questions, since none of those were able to provide this answer)

解决方案

If you don't need to work in place, then maybe something like:

with open("old.txt") as f_old, open("new.txt", "w") as f_new:
    for line in f_old:
        f_new.write(line)
        if 'identifier' in line:
            f_new.write("extra stuff\n")

(or, to be Python-2.5 compatible):

f_old = open("old.txt")
f_new = open("new.txt", "w")

for line in f_old:
    f_new.write(line)
    if 'identifier' in line:
        f_new.write("extra stuff\n")

f_old.close()
f_new.close()

which turns

>>> !cat old.txt
a
b
c
d identifier
e

into

>>> !cat new.txt
a
b
c
d identifier
extra stuff
e

(Usual warning about using 'string1' in 'string2': 'name' in 'enamel' is True, 'hello' in 'Othello' is True, etc., but obviously you can make the condition arbitrarily complicated.)

这篇关于使用 Python 在特定文本之后将文本插入到文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆