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
时间: 2024-10-07 05:31:41