File Positions

  1. tell method 取得目前在檔案的讀寫位置。seek(offest[n, from]) method 改變目前的讀寫位置,n 是移動的 bytes 數,from 是開始的位置,from 設定值:
    1. 0:檔案的開頭;
    2. 1:目前位置;
    3. 2:檔案結尾。
  2. 範例:讀 10 bytes 後,使用 tell 查看目前的讀取位置。使用 seek 將讀取位置移到檔案開頭,再次讀取 10 bytes。
    [dywang@deyu zzz]$ cat fileio5.py 
    #!/usr/bin/python3
    
    fo = open("fileio.txt", "r+")
    print("Read 10 bytes is:", fo.read(10))
    print("Current file position:", fo.tell())
    fo.seek(0,0)
    print("Current file position after seek:", fo.tell())
    print("Again read 10 bytes is:", fo.read(10))
    fo.close()
    
  3. 執行結果:第一次讀取10個字後,讀取位置在 16,6個字元加1個空白,每個中文字3個位元組,所以位置在16,使用 seek 後回到 0,再次讀取還是從檔案開頭讀取。
    [dywang@deyu zzz]$ ./fileio5.py 
    Read 10 bytes is: Python 是很棒
    Current file position: 16
    Current file position after seek: 0
    Again read 10 bytes is: Python 是很棒