I have a code, that is supposed to write a text file, and then replace some text in one line with something else.
def read(text):
file = open('File.txt', 'r+') #open the file for reading and writing
x = file.readline() # read the first line of the file
file.seek(0, 0) #put the pointer back to the begining
file.readline() #skip one line
file.write(text) #write the text
file.close() #close the file
read('ABC')
At the beginning it's fine. It reads the first line and sets pointer to the beginning of the file. But then when it's supposed to read one line and put the pointer at the second line, it puts it at the end of the file. If I assign that to a variable, it only reads one line, but it still sets the pointer at the end of the file.
Apparently readline() doesn't work as I thought it was, so please tell me how I could read some lines of the text and the write something to the specific line.
Writing, by default, always takes place at the end of the file. Calling file.readline() doesn't change this behaviour, especially since readline() calls can use a buffer to read in larger blocks.
You could override by using file.seek() explicitly to go to the end of a line; you just read the line, you know the length, seek to that point:
x = file.readline()
file.seek(len(x), 0)
file.write(text) #write the text
Note that you cannot insert lines, or easily replace lines. A file is a stream of individual bytes, not lines, so if you write in a line of 10 characters (including the newline) you can only replace that line with 10 other characters. Longer or shorter lines won't work here; you are just going to replace fewer or more characters in the file and either partially replace a line or overwrite (part of) the next line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With