python中seek函数_Python seek()函数

"""

注:在windows中,换行符是\r\n,为2个字符,而在linux中,换行符是\n,为1个字符

f.seek(offset,whence)

offset:偏移量,即偏移(略过)多少个字符开始读取,默认为0

whence:0-->从头开始读取,1-->当前位置继续读取,2-->末尾开始读取

为方便显示文件换行符,尝试用notepad打开,视图-->显示符号-->显示所有符号

另:

当查阅不到文档时,尝试:help(obj.attribute)

"""

with open('4.缓冲区.py.txt', 'r', encoding='utf-8') as f:

# print(f.tell()) # 0

# line = f.readline()

# print(repr(line), len(line)) # 'hello world!\n' 13

# f.seek(1)

# print(f.tell()) # 1

# line = f.readline()

# print(repr(line), len(line)) # 'ello world!\n' 12

# 按理来说,一行13个字符,偏移(略过)13个后应该读取第二行内容,实际结果却是:'\n'

# 为何?hello world!共12个字符,换行符为\r\n

# 读取到\r时,被认为是一行,共13个字符

# 故偏移13个字符再次读取到的是'\n'

# windows中,应该偏移len()+1个字符才能读取到下一行内容

# f.seek(13, 0)

# print(f.tell()) # 13

# line = f.readline()

# print(repr(line), len(line)) # '\n' 1

# 2行,1行12个,2行24个,加\r\n,共26个字符

# 当文件指针已经在EOF(文件末尾处),则将读取''

# f.seek(0, 2)

# print(f.tell()) # 26

# line = f.readline()

# print(repr(line), len(line)) # '' 0

# Python3中,当whence=2时,offset必须为0,正负数都不行

f.seek(-10, 2)