|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
求大神指教
报错是:
Traceback (most recent call last):
File "E:\Python\029课后作业打印指定行.py", line 44, in <module>
file_view(file_name,line_num)
File "E:\Python\029课后作业打印指定行.py", line 26, in file_view
end = int(end)
ValueError: invalid literal for int() with base 10: ''
其他都正常,就是输入 : 的时候不会打印全文:
- def file_view(file_name,line_num):
- if line_num.strip() == ':':
- begin = '1'
- end = '-1'
- (begin,end) = line_num.split(':')
- if begin == '':
- begin = '1'
- elif 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 ('\n文件%s%s的内容如下:\n' % (file_name,prompt))
- begin = int(begin)-1
- end = int(end)
- lines = end - begin
- f = open(file_name)
- for i in range(begin):
- f.readline()
- if lines < 0:
- print (f.read())
- else:
- for j in range(lines):
- print (f.readline(),end='')
- f.colse()
- file_name = input('请输入要打开的文件(C:\\test.txt):')
- line_num = input('请输入要打印的范围【格式如 13:21 或 :21 或 13: 】:')
- file_view(file_name,line_num)
-
复制代码
你在第3行第4行给输入':'的时候赋值begin和end,但是马上就被第6行的(begin,end) = line_num.split(':')将赋值改为了'',第10行是elif,也就是说只有begin不为空的时候才会去判断end是否为空,这时候输入的是':'的时候就会出现end不会被重新赋值为'-1'而保持为'',下面的int(end)当然就会报错。还有你的f.close()输错了。
- 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 == '': #elif改成if
- 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 ('\n文件%s%s的内容如下:\n' % (file_name,prompt))
- begin = int(begin)-1
- end = int(end)
- lines = end - begin
- f = open(file_name)
- for i in range(begin):
- f.readline()
- if lines < 0:
- print (f.read())
- else:
- for j in range(lines):
- print (f.readline(),end='')
- f.close() #修改一下错误
- file_name = input('请输入要打开的文件(C:\\test.txt):')
- line_num = input('请输入要打印的范围【格式如 13:21 或 :21 或 13: 】:')
- file_view(file_name,line_num)
-
复制代码
|
|