学习要点
f.seek(0)
意思是回到文件的第一个字节位置,也就是文件开始。f.readline()
读取文件每一行,直到找到一个\n
为止,然后它就停止读取文件,并且返回之前发现的文件内容。同时文件记录每次调用'readline()'后的读取位置,这样它就可以在下次被调用时读取接下来的一行。+=
意思是x += y
表示x = x + y
。
程序代码
from sys import argv
script, input_file = argv
def print_all(f):
print(f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count,f):
print(line_count,f.readline(),end='')
current_file = open(input_file)
print("Frist let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")
rewind(current_file)
print("Let's print three lines:")
current_line = 1
print_a_line(current_line,current_file)
current_line = current_line + 1
print_a_line(current_line,current_file)
current_line = current_line + 1
print_a_line(current_line,current_file)
输出结果
PS D:\lpthw> python ex20.py test.txt
Frist let's print the whole file:
Mary had a little lamb
It's fleece was white as snow
It was also tasty
Now let's rewind, kind of like a tape.
Let's print three lines:
1 Mary had a little lamb
2 It's fleece was white as snow
3 It was also tasty