Answers for "how to write to a specific line in a file python"

0

how to write to a specific line in a file python

# An alternate approach would be to write a function to yield lines until it sees an xxxxx\nyyyyy\n
def getlines(fobj,line1,line2):
     for line in iter(fobj.readline,''):  #This is necessary to get `fobj.tell` to work
         yield line
         if line == line1:
             pos = fobj.tell()
             next_line = next(fobj):
             fobj.seek(pos)
             if next_line == line2:
                 return
# Then you can use this passed directly to writelines:
with open('input') as fin, open('output','w') as fout:
    fout.writelines(getlines(fin,'xxxxx\n','yyyyy\n'))
    fout.write('my_line\n')
    fout.writelines(fin)
Posted by: Guest on February-24-2022
0

how to write to a specific line in a file python

with open('input') as fin, open('output','w') as fout:
    for line in fin:
        fout.write(line)
        if line == 'xxxxx\n':
           next_line = next(fin)
           if next_line == 'yyyyy\n':
              fout.write('my_line\n')
           fout.write(next_line)
Posted by: Guest on February-24-2022

Code answers related to "how to write to a specific line in a file python"

Python Answers by Framework

Browse Popular Code Answers by Language