文件倒讀
阿新 • • 發佈:2017-07-03
文件倒讀
文件倒讀
In [1]: cat /tmp/1.txt a b c d In [2]: ll /tmp/1.txt 應該是有8個字符,每個字符後邊都有一個換行符號\n,加上換行符共8個字節。 -rw-r--r-- 1 admin wheel 8 7 3 15:18 /tmp/1.txt In [3]: f = open(‘/tmp/1.txt‘) In [4]: f.tell() 指針位置:0 在文件的開頭 Out[4]: 0 In [5]: f.read(1) 讀一個字符 Out[5]: ‘a‘ In [6]: f.tell() 指針位置:1 Out[6]: 1 In [13]: f.read(1) 讀一個字符 Out[13]: ‘\n‘ In [14]: f.tell() 指針位置:2 Out[14]: 2 In [15]: f.read(2) 讀2個字節,b和\n Out[15]: ‘b\n‘ In [16]: f.tell() 指針位置:4 Out[16]: 4 In [17]: f.read(100) Out[17]: ‘c\nd\n‘ In [18]: f.tell() Out[18]: 8 In [30]: help(f.seek) Help on built-in function seek: seek(...) 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. 0 從開頭指針位置移動 In [45]: f.seek(2) In [46]: f.tell() Out[46]: 2 In [10]: f.seek(0,0) 移動指針到開頭,從開頭向後移動0位 In [11]: f.tell() Out[11]: 0 1 從當前指針位置移動 f.tell() Out[42]: 5 In [43]: f.seek(-2,1) In [44]: f.tell() Out[44]: 3 2 從結尾的指針位置開始移動move relative to end of file In [8]: f.seek(3,2) 8+3=11從結尾8向後移動三位, In [9]: f.tell() Out[9]: 11 In [12]: f.seek(0,2) 把指針移動到最後 In [13]: f.tell() Out[13]: 8
admindeMacBook-Air-62:~ admin$ cat /tmp/1.txt a b c d #!/usr/bin/env python f = open(‘/tmp/1.txt‘) f.seek(0,2) while True: if f.tell() == 1: break else: f.seek(-2,1) c = f.read(1) print c, python seek.py d c b a #!/usr/bin/env python #encoding:utf8 import sys f = open(‘/etc/hosts‘) f.seek(0,2) line = ‘‘ while True: if f.tell() == 1: print line #打印1a的條件 break else: f.seek(-2,1) c = f.read(1) if c != ‘\n‘: line = c + line #空+d=d,4+d=4d else: print line line = ‘‘ #重置line=空 python seek3.py 221.228.208.76 dmp.chinadep.com admin.chinadep.com
本文出自 “梅花香自苦寒來!” 博客,請務必保留此出處http://daixuan.blog.51cto.com/5426657/1944180
文件倒讀