欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

笨办法学Python3 习题20

程序员文章站 2022-03-05 14:31:06
...

基于Python3.6

习题20

from sys import argv
#从命令行输入要读取的文件
script, input_file = argv
#定义输入全部文件内容的函数
def print_all(f):
    print(f.read())
#seek()方法用于移动文件读取指针到指定位置,0是文件开头
def rewind(f):
    f.seek(0)
#定义打印某一行的文件函数,readline()自动换行
def print_a_line(line_count, f):
    print(line_count, f.readline())

current_file = open(input_file)

print("First 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)

 

 

 
相关标签: 代码学习