Python在特定行之前插入文本

时间:2014-08-16 06:48:54

标签: python regex

我想在一行' Number'。

之前专门插入一个文字

我想插入“Hello Everyone'以' Number'

开头的行

我的代码:

import re
result = []
with open("text2.txt", "r+") as f:
    a = [x.rstrip() for x in f] # stores all lines from f into an array and removes "\n"
    # Find the first occurance of "Centre" and store its index
    for item in a:
        if item.startswith("Number"): # same as your re check
            break
    ind = a.index(item) #here it produces index no./line no.
    result.extend(a[:ind])
        f.write('Hello Everyone')

tEXT文件:

QWEW
RW
...
Number hey
Number ho

预期产出:

QWEW
RW
...
Hello Everyone
Number hey
Number ho

请帮我修改我的代码:我的文本文件没有插入任何内容!请帮忙! 答案将不胜感激!

3 个答案:

答案 0 :(得分:2)

问题

执行open("text2.txt", "r")后,您打开文件阅读,而不是。因此,您的文件中不会显示任何内容。

修复

使用r+而不是r允许您也写入文件(注释中也指出了这一点。但是,它会覆盖,所以要小心(这是一个操作系统限制,如here所述。以下应该按照您的意愿执行:它将"Hello everyone"插入行列表,然后用更新的行覆盖文件。

with open("text2.txt", "r+") as f:
    a = [x.rstrip() for x in f]
    index = 0
    for item in a:
        if item.startswith("Number"):
            a.insert(index, "Hello everyone") # Inserts "Hello everyone" into `a`
            break
        index += 1
    # Go to start of file and clear it
    f.seek(0)
    f.truncate()
    # Write each line back
    for line in a:
        f.write(line + "\n")

答案 1 :(得分:2)

问题的正确答案是hlt,但请考虑使用fileinput模块:

import fileinput

found = False
for line in fileinput.input('DATA', inplace=True):
    if not found and line.startswith('Number'):
        print 'Hello everyone'
        found = True
    print line,

答案 2 :(得分:1)

这与here基本相同:他们建议分三步完成:读取所有内容/插入/重写所有内容

with open("/tmp/text2.txt", "r") as f:
lines = f.readlines()

for index, line in enumerate(lines):
    if line.startswith("Number"):
        break
lines.insert(index, "Hello everyone !\n")

with open("/tmp/text2.txt", "w") as f:
    contents = f.writelines(lines)