使用file.seek():
import osfind_str = "ERROR"error = False# Open file with 'b' to specify binary modewith open(file_directory, 'rb') as file: file.seek(-1024 * 1024, os.SEEK_END) # Note minus sign if find_str in file.read(): error = True
打开文件时必须指定二进制模式,否则会出现“未定义的行为”。在python2下,它仍然可以工作(对我而言确实如此),但是在python3下,如果以默认文本模式打开文件,
seek()则会引发
io.UnsupportedOperation异常。python
3文档在这里。尽管这些文档尚不清楚,但
SEEK_*常量仍在
os模块中。
更新: 克里斯·贝蒂(Chris
Betti)建议使用
with语句进行更安全的资源管理。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)