from sys import argv
srcipt, input_file = argv
def print_all(fp):
print(fp.read())
def print_oneline(line_count,fp):
print(line_count, fp.readline(), end = "")
def rewind(fp):
fp.seek(0)
fp=open(input_file)
print("Let's print the whole file:")
print_all(fp)
print("now let's rewind, kind of like a tape.")
rewind(fp)
print("Let's print three lines:")
count=1
print_oneline(count, fp)
count += 1
print_oneline(count, fp)
count += 1
print_oneline(count, fp)
print("")
结果为:
*seek()
函数处理的是字节而非行,seek(0)
只是转到文件的0
字节位置
*readline()
会扫描文件的每一个字节,直到找到一个‘\n’
为止
*
文件会记录每次调用readline()后的读取位置
*readline()
返回的内容有‘\n’,因此要在print中加入一个参数: end=""