|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def file_view(file_name,line_num):
if line_num.strip() == ':':
begin = '1'
end = '-1'
(begin,end)=line_num.split(':')
if begin == '':
begin = '1'#为什么要定义为字符串形式
if end == '':
end = '-1'
if begin == '1' and end == '-1':
prompt = '的全文'
elif begin == '1':
prompt = '从开始到%s'% end
elif end == '-1':
prompt = '从%s到结束' % begin
else:
prompt = '从第%s行到第%s行'% (begin,end)
print('文件%s%s的内容如下:'%(file_name,prompt))
begin = int(begin)-1
end = int(end)
lines = end - begin
f = open(file_name)
for i in range(begin):#用于消耗掉begin之前的内容
f.readline()
if lines < 0:
print(f.read())
else:
for j in range(lines):
print(f.readline(),end='')
f.close()
file_name = input('请输入要打开的文件:')
line_num = input('请输入要显示的行数【格式如13:21或:21或13:或:】')
file_view(file_name,line_num)
1 方便接受字符串的spilt函数结果,另外也方便print输出的时候用%s
2 begin前面的所有字符不显示,所以先将文件指针指向begin那一行
|
|