在文件中的当前行之上写一行 Python

Write a line above the current line in a file Python

我正在遍历一个文件,我需要在匹配特定字符串的行上方插入一个文本块。请帮忙!

 convBlockMoved = False
 for line in outfile:
    if(line.startswith('mappingSchemeAxis') and not convBlockMoved):
       for convLine in conversionBlocks:
            print convLine, #Print this above line
            convBlockMoved = True

注意:conversionBlocks 是一个字符串数组

试试这个:

def replace_import_in_f(f_in, pattern, plus):
    with open(f_in) as f:
        in_str = f.read()
        in_str = re.sub(pattern, pattern + plus + "\n", in_str)
    with open(f_in, "w") as f:
        f.write(in_str)

模式必须是您要在上面添加新行的整行。

注意:由于整个文件内容的 f.write(),这非常适合中等文件。 (用 python 3.4 测试)

[更新]

更复杂但要处理大文件,在行处理期间使用协程写入临时文件。如果没有错误,请替换临时文件。

import tempfile, os

def write_file(pattern="", plus=""):
    with tempfile.NamedTemporaryFile(delete=False) as fin:
        yield fin
        while True:
            line = (yield)                
            if pattern:
                if line.startswith(pattern):
                    fin.write(bytes(plus, 'UTF-8'))
            fin.write(bytes(line, 'UTF-8'))

def copy_file(path_in, path_out):
    with open(path_in) as fin, open(path_out, "w") as fout:
        for line in fin:
            fout.write(line)


def read_and_file(fname, pattern="", plus=""):
    try:
        with open(fname) as fh:
            # generator creation
            gen_write = write_file(pattern, plus)
            # get the tempfile
            fout = next(gen_write)
            for line in fh:
                # send line
                gen_write.send(line)
    except (IOError, OSError) as e:
        print(e)
    else:
        fout.close()
        if os.name == "nt":
            copy_file(fout.name, fname)
        else:
            os.rename(fout.name, fname)

不是 Python 答案,但 sed 可以在一行中完成。

文件:

$ cat > so.txt
foo
bar
baz
qux

在行前插入 baz:

$ sed -i '/baz/i11\n22\n33' so.txt

结果:

$ cat so.txt
foo
bar
11
22
33
baz
qux

因此,如果您的文件不是很大,您可以一次读取所有行,然后使用列表。使用列表的插入方法的示例是:

def main():
    lines = []
    with open('input.txt') as f:
        lines = f.readlines()

    ins_at = find_occurences_of('mappingSchemeAxis', lines)

    for i in ins_at:
        lines.insert(i,'HELLO WORLD\n')

    with open('input.txt', 'w') as f:
        f.writelines(lines)

def find_occurences_of(needle, haystack):
    ret = []
    for i, line in enumerate(haystack):
        if line.startswith(needle):
            ret.append(i)
    return ret 

if __name__ == '__main__':
    main()

基本上,您正在读取一个字符串列表,并且您希望在某些条件下将一个新的列表元素放在当前列表元素之上。

我建议您(如果文件不是太大)将输入的行附加到输出列表,在符合您条件的每一行之前附加您想要的文本。类似下面的内容

for line in infile.readlines ():
    if line.startswith ('mappingSchemeAxis'):
        outcontent.append ('xxxxx')

    outcontent.append (line)


for line in outcontent:
    print (line) # here you want to write the content to the output file

我发帖有点晚了:D