0

I am new to python. I am tasked with creating a gui. The gui is fine but one of the buttons alters another python script. I have gotten the other script to open successfully. I do not want to open with 'w' because I need what is in it. 'a+' does not help becuase I need to change the code in the middle not at the end. Lastly, I am having difficulty with 'r+'. This is the code.

with open("test.py", "r+") as f
    #f.seek(14)
    #f.readline()
    f.write('what is going on.\nI am very confused')

Readline always took it to the end of the other script. And I have 0 idea what seek did.

The actual file that will replace "test.py" will be 1000+ lines and I need to write on line 532. That is what I am asking how to do. There will be code on the line above and below 532 that I can not delete while adding a 8 line block.

Byrge
  • 9
  • 4
  • 1
    Please post the actual code into the question, not a link to a screen shot. – Mark Ransom Jun 25 '18 at 16:10
  • You cannot replace a line in a file unless the new line is exactly the same size as the one you're replacing. Usually you will read the entire file and write it back out with the line replaced. – Mark Ransom Jun 25 '18 at 21:57
  • I am just looking to add a new block. So it's a block that has stored barcodes. I want to add another barcode to that segment. – Byrge Jun 26 '18 at 19:24

1 Answers1

0

This is what seek does -

>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)      # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)  # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'

If you want to append in middle of file, see this answer - https://stackoverflow.com/a/10507291/8010361

dedsec
  • 59
  • 1
  • 9
  • That answer is helpful, but what if I do not want it in a list? It's just a code block. I don't want that in a list. – Byrge Jun 25 '18 at 18:12