python阅读器代码
最近在学习python,作业是用python写一个阅读器:
要求如下:
1,有自动阅读模式
2,可以上下翻页
实战:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#coding:utf-8 import time
tl = [] #用于存放位置
def readers(path,lines = 5 ,auto = False ,times = 3 ):
with open (path, "r" ) as f:
f.seek( 0 , 2 ) #移动到末尾
last = f.tell() #记住末尾位置
f.seek( 0 ) #移动到文档首部
for i in range (lines): #先阅读几行
print (f.readline())
tl.append(f.tell()) #记录位置到列表
if auto = = True : #自动阅读
while f.tell() < last:
for i in range (lines):
print (f.readline())
time.sleep(times)
else :
while f.tell() < last:
contorl = raw_input ( "输入N|n向下翻页,M|m向上翻页,Q|q退出阅读! >>>" )
if contorl = = "q" or contorl = = "Q" :
print ( "您选择退出阅读!" )
break
elif contorl = = "n" or contorl = = "N" :
for i in range (lines):
print (f.readline()),
tl.append(f.tell())
elif contorl = = 'm' or contorl = = "M" :
if len (tl) = = 1 :
print ( "已经是首页啦!" )
continue
elif len (tl) = = 2 :
f.seek( 0 )
for i in range (lines):
print (f.readline()),
tl.pop()
continue
else :
f.seek(tl[ - 3 ])
for i in range (lines):
print (f.readline()),
tl.pop()
print ( "已经到文章底部了!" )
if __name__ = = "__main__" :
#readers("1.txt",auto=True,lines=6,times=5)
readers( "1.txt" )
|
测试:
可以修改为自动阅读模式和时间,以下是手动翻页阅读结果:
写的不是很好,如有不当之处,欢迎指正交流~
本文转自 dyc2005 51CTO博客,原文链接:http://blog.51cto.com/dyc2005/1940858,如需转载请自行联系原作者