0

I have copied a certain part of a .txt file into a list. I need to go to particular line and paste/append it.

file = open(filepath, 'r')
with open(filepath) as f:   # SEARCH IF STAGE1 & STAGE2 EXIST OR NOT
    if 'stage1' in f.read():
        print("stage 1")
        data = file.readlines()[11:26]
        print(*data, sep='')
        with open(filepath) as f:
            srno = f.readlines()[7:8]
            print(*srno, sep='')

Now that I've copied lines 11-26 and line 7-8.. I want to paste/append it in the text file above line 5. How would I go about doing that?

I've written this but it only appends it to the end of the text file.

 with open(filepath, 'a+') as fa:
        fa.writelines(srno)
        fa.writelines("M0\n\n")
        for i in data:
            fa.writelines(i)
    file.close()

I want to write what I've copied in 'data' and 'srno' to line 5 in the text file.

f0rty
  • 15
  • 6
  • 2
    Does this answer your question? [Insert line at middle of file with Python?](https://stackoverflow.com/questions/10507230/insert-line-at-middle-of-file-with-python) – Green绿色 Mar 09 '22 at 08:44
  • I tried doing it but my whole text file just goes blank now. Also my 'value' is a list so I don't know if that would work since my 'value' is 'data = file.readlines()[11:26]' – f0rty Mar 09 '22 at 09:02

0 Answers0