函数和文件
- 输入:
# -*- coding: utf-8 -*-
from sys import argv
script, input_file = argv
def print_all(f):
print f.read() # 将参数文件的内容读出来
def rewind(f):
f.seek(0)
# 重新从起始位开始,如果没有seek,在第一次读取内容后,’光标’在最后,第二次就没有内容可以读取了
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, kine 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)
-
运行: