So I'm trying to read the second to last number in a file. My code is as follows:
file = open("file.txt", "rb")
print (file.seek(-2, 2))
file.close()
The contents of my file are as follows:
1,2,1,1,2,0,1,1,2,1,1,1,0,0,0,0,1,2,0,0,0,1,0,1,1,0,0,0,1,0,0,2,1,1,
I expected the program to print "1" but it actually prints "3" Does anyone know why this is and how to fix it? Thanks!
It's worth noting that seek
operates by an offset of characters (or bytes in binary mode). Each comma separating the numbers in your example is going to count as a character (or byte in your case since you did open in binary mode). In order to read the second to last number in the example you provided, you would need to seek back 4 characters (2 numbers and 2 commas, since your file ends in a comma), then read a single character
f.seek(-4, 2)
r.read(1)
Realize that this won't work if any of the numbers are larger than 1 digit. Looking at your file, it doesn't appear to be written in binary, so opening it in binary mode doesn't make much sense. If the file is small enough to fit into memory, it would be simpler and less error prone to read the whole file, then parse it to get the second to last number
number = int(f.read().strip(',').split(',')[-2])
The return value of seek
is not anything read from the file. On Python 2, the return value is None
; on Python 3, the return value is a number representing the new absolute position in the file, which may not correspond to the number of bytes or characters from the start of the file in text mode.
If you want to read a character after seeking, call file.read(1)
.
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