|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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('\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): # 用于消耗掉begin之前的内容
- f.readline()
- if lines < 0:
- print(f.read())
- else:
- for j in range(lines):
- print(f.readline(), end='')
-
- f.close()
- file_name = input(r'请输入要打开的文件(C:\\test.txt):')
- line_num = input('请输入需要显示的行数【格式如 13:21 或 :21 或 21: 或 : 】:')
- file_view(file_name, line_num)
复制代码
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='')
这段看不懂
本帖最后由 sunrise085 于 2020-4-8 17:19 编辑
每调用一次f.readline(),文件指针就会向后移动一行。
通过这个for循环,将文件指针移动到打算输出的那一行。for循环,f.readline()仅仅是读取了一行,并把光标下移一行,但是没有进行其他操作,其目的就是移动文件指针光标而已。
千万不要用seek逐行移动文件指针
1、seek与编码无关,同样的内容不同的编码下字符数不一样,你很难确定移动多少个字符;
2、打开文件的时候,你也不知道文件的每一行的内容是什么,也就不可能是用seek精确地移动光标到指定 的那一行的开头位置。
|
|