It's intersting I can not put the "offset" to non-zero if I set the second parameter as "1" or "2" in file.seek(), and please refer to the below screenshot for more details.
I don't believe it's a bug of Python Idle environment, but how to explain and fix it?
[
attachment=715]
With the right whence-flag, you can use negative numbers.
Look here:
https://docs.python.org/3/library/io.htm...OBase.seek
In [1]: from pathlib import Path
In [2]: raspbian = Path('Downloads/2019-07-10-raspbian-buster-lite.zip')
In [3]: with raspbian.open('rb') as fd:
...: print('Size:', raspbian.stat().st_size)
...: print('Pos:', fd.tell())
...: print('Seek to -10 bytes from end')
...: fd.seek(-10, 2)
...: print('New position:', fd.tell())
...:
Size: 426250971
Pos: 0
Seek to -10 bytes from end
New position: 426250961
Instead of recognizing the number for 'whence', you can use os.SEEK_END:
In [10]: print(os.SEEK_SET, os.SEEK_CUR, os.SEEK_END)
0 1 2
In addition, I've used pathlib.Path, which is better to handle.
You can still use the built-in function
open()
.
The resulting file-object is the same as from
Path.open(mode)
.
(Sep-27-2019, 11:46 AM)Gribouillis Wrote: [ -> ]What is csv_file
?
csv_file = open("1.csv", "r")
I don't want to use any additional module, saying "os", because it's a simple work to seek backward with "file.seek". Just confused why it doesn't work as descripted.
The negative seek works if the file is opened in binary mode 'rb'.
(Sep-27-2019, 07:01 PM)Gribouillis Wrote: [ -> ]The negative seek works if the file is opened in binary mode 'rb'.
Thank you so much, it's really the root cause!
May I know why it only works in "rb" mode? Why not in "r" mode?
Found the explaination on internet, and thank you again.