软件版本
Python 2.7.13; Win 10
场景描述
1、使用python读取指定长度的文本;
2、使用python读取某一范围内的文本。
Python代码
test.txt文本内包含的字符串为“AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD”,A,B,C,D均为8个
# -*- coding:utf-8 -*-
text_file = r"test.txt"
# open()
f = open(text_file, "r")
# 以文件起始位置作为相对位置,偏移8个长度
f.seek(8, 0)
# 输出当前指针偏移量
pos = f.tell()
print pos
# 读取8个字节长度的文本,范围为[8,16)
text_to_number = f.read(8)
print text_to_number
# 输出当前指针偏移量,可以观测到read()也会造成文件指针偏移
pos = f.tell()
print pos
# 以当前文件指针作为相对位置,偏移8个长度
f.seek(8, 1)
# 读取8个字节长度的文本,范围为[24,32)
text_to_all = f.read(8)
print text_to_all
f.close()
输出:
8
BBBBBBBB
16
DDDDDDDD