python文件seek_Python文件读取中:f.seek(0)和f.seek(0,0)有什么区别?
2016-06-06 回答
你好!
>>> print f.seek.__doc__
seek(offset[, whence]) -> None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
>>>
f.seek的參數說明如上。
僅代表個人觀點,不喜勿噴,謝謝。
追問:
大哥,看不懂啊,能解釋下不?
追答:
回答你的問題:
1. whence 的默認參數是0。
所以seek(0)和f.seek(0,0)沒有區別。
2. whence 還有兩種情況 是1,或者2
3. 1的時候,相對當前坐標的移動,可以是正的也可以是負的。
2的時候相對于文件結束的移動,通常應該是負的。
追問:
移動是指怎么移動?
追答:
>>>?f.readlines()#讀取出文件的所有內容
['abcdefghijk\n']
>>>?f.seek(2)?#將當前的位置設定為相對當前位置的2的位置。
>>>?f.read(4)?#讀取4個位置的數據(從設定的位置開始讀取,也就是ab?后面的四個字符)
'cdef'
>>>?f.seek(2,1)#將當前的位置(2)設定為相對當前位置的2的位置。
>>>?f.read(4)#?在讀取四個位置的數據
'ijk\n'
>>>?f.seek(2,2)
>>>?f.read(4)
''
>>>?f?=?open(r"c:\input.txt","r")
>>>?f.readlines()#將當前的位置設定為相對當前位置的2的位置。
['abcdefghijk\n']
>>>?f.seek(2,0)#將當前的位置設定為相對當前位置的2的位置。
>>>?f.read(4)#讀取4個位置的數據(從設定的位置開始讀取,也就是ab?后面的四個字符)
'cdef'
>>>?f.seek(2,1)#將當前的位置(2)設定為相對位置的2的位置,也可以是負值,賦值是向前移動。
>>>?f.read(4)??#再讀取四個位置的數據
'ijk\n'
>>>?f.seek(-2,2)#將當前的位置設定為相對文件結束為-2的位置,就是距離文件結束還有兩個位置
>>>?f.read(2)?#讀取二個位置的數據
'\n'
>>>不明白在追問吧
總結
以上是生活随笔為你收集整理的python文件seek_Python文件读取中:f.seek(0)和f.seek(0,0)有什么区别?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mac macOs Big Sur 版本
- 下一篇: 逆矩阵 求矩阵的逆