Write a line above the current line in a file Python

3k views Asked by At

I am looping through a file and I need to insert a text block above a line when it matches a particular string. Please help!

 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

Note: conversionBlocks is a String array

4

There are 4 answers

0
Salo On BEST ANSWER

So if your file is not huge, you can read all the lines at once and then work with lists. An example using the insert method of lists would be:

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()
2
Ali SAID OMAR On

Try this:

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)

Pattern must be the entire line that you would add the new line above.

Note: This is perfect for medium file due to the f.write() of the whole file content. (Test with python 3.4)

[UPDATE]

More complicated but to handle big files, use of coroutine to write to temp file during line processing. If not error replace the temp file.

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)
0
AudioBubble On

Not a Python answer, but sed can do this in one line.

The file:

$ cat > so.txt
foo
bar
baz
qux

Insert before line baz:

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

The result:

$ cat so.txt
foo
bar
11
22
33
baz
qux
0
Carlo Lobrano On

Basically, you are reading a list of strings and you want to put a new list element above the current one under some conditions.

What I would suggest you (if the file is not too big) is to append the lines from your input to an output list, appending the text you want before each lines that matche your conditions. Something like the following

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

I posted that a bit late :D