笨辦法學Python:函數和文件
阿新 • • 發佈:2017-11-11
bsp ack win nes 分享 技術 什麽 div color
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(),
笨辦法學Python:函數和文件