Ex20 Functions and Files

函数与文件操作

闲言少叙,看代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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()
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)
current_line = current_line + 1
print_a_line(current_line, current_file)

运行结果如图:

小结

Ex 20 把函数和文件组合在一起。需要查询文档关于 readline() 函数的种种说明。另外, 在自定义的 print_a_line() 函数里,行号实现方式。 最后,需要思考 seek() 函数的用意。

Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计