笨办法学Python:函数和文件
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)
常见问题之Q2: 文件中为什么有3个空行?
函数 readline() 返回一行以 \n 结尾的文件内容, 在你调用print函数的最后增加一个逗号',',用来避免为每一行添加两个换行符 \n
def print_a_line(line_count,f): print line_count,f.readline(),