簡體   English   中英

使用Python將文本插入特定文本后的文本文件中

[英]Insert text into a text file following specific text using Python

我必須編輯一些文本文件以包含新信息,但我需要根據周圍的文本在文件中的特定位置插入該信息。

這不是我需要它的方式:

 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')

...因為它將文本添加到文件的末尾。 如何將其寫入識別文本后的下一行?

(AFAICT,這不是類似問題的重復,因為沒有一個能夠提供這個答案)

如果您不需要在適當的地方工作,那么可能是這樣的:

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")

(或者,兼容Python-2.5):

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()

轉過來

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

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

(關於在'string2'中使用'string1'的常見警告:'enamel'中'name'為True,''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

您可以使用正則表達式,然后替換文本。

import re
c = "This is a file's contents, apparently you want to insert text"
re.sub('text', 'text here', c)
print c

返回“這是文件的內容,顯然你想在這里插入文字”

不確定它是否適用於您的用例但如果它適合它就很好而且簡單。

這將在文件中查找任何字符串(不具體,僅在行的開頭,即也可以存在於多行中)。

通常情況下,你可以遵循算法:

  1. 查找文件中的字符串,並捕獲“位置”
  2. 然后拆分有關此“位置”的文件,並嘗試創建新文件
    • 將start-to-loc內容寫入新文件
    • 接下來,將“NEW TEXT”寫入新文件
    • 接下來,將loc-to-end內容發送到新文件

讓我們看看代碼:

#!/usr/bin/python

import os

SEARCH_WORD = 'search_text_here'
file_name = 'sample.txt'
add_text = 'my_new_text_here'

final_loc=-1
with open(file_name, 'rb') as file:
        fsize =  os.path.getsize(file_name)
        bsize = fsize
        word_len = len(SEARCH_WORD)
        while True:
                found = 0
                pr = file.read(bsize)
                pf = pr.find(SEARCH_WORD)
                if pf > -1:
                        found = 1
                        pos_dec = file.tell() - (bsize - pf)
                        file.seek(pos_dec + word_len)
                        bsize = fsize - file.tell()
                if file.tell() < fsize:
                                seek = file.tell() - word_len + 1
                                file.seek(seek)
                                if 1==found:
                                        final_loc = seek
                                        print "loc: "+str(final_loc)
                else:
                                break

# create file with doxygen comments
f_old = open(file_name,'r+')
f_new = open("new.txt", "w")
f_old.seek(0)
fStr = str(f_old.read())
f_new.write(fStr[:final_loc-1]);
f_new.write(add_text);
f_new.write(fStr[final_loc-1:])
f_new.close()
f_old.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM