標籤:Python 函數
# -- coding: utf-8 --# 從sys模組匯入argv函數from sys import argv# 利用argv函數,把 argv 中的東西解包,將所有的參數依次賦予左邊的變數名script, input_file = argv# 自訂一個函數,讀取f的內容def print_all(f): print f.read()# 自訂函數,使用file中的seek方法來移動檔案遊標,用於依次讀取檔案行的功能def rewind(f): f.seek(0)# 該指令碼的主函數,用於列印檔案每一行的內容def print_a_line(line_count, f): print "No.", line_count, f.readline()# 使用file中的open方法來開啟檔案current_file = open(input_file)print "First let‘s print the whole file:\n"# 使用自訂的函數print_all來讀取開啟的檔案內容print_all(current_file)print "Now let‘s rewind, kind of like a tape."# 使用上面自訂的函數rewindrewind(current_file)print "Let‘s print three lines:"# 定義一個變數,每列印完一行就加1,把這個變數作為print_a_line函數的參數,調用print_a_line函數可以依次列印每一行。# 下面的幾行代碼可以採用迴圈來寫,以減少代碼長度。current_line = 1print "Now Current line is : %d" % current_lineprint_a_line(current_line, current_file)current_line = current_line + 1print "Now Current line is : %d" % current_lineprint_a_line(current_line, current_file)current_line = current_line + 1print "Now Current line is : %d" % current_lineprint_a_line(current_line, current_file)
使用python的協助來查詢seek方法的內容
python -m pydoc file
seek(...)
seek(offset[, whence]) -> None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1(move relative to current position, positive or negative), and 2 (moverelative to end of file, usually negative, although many platforms allowseeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable.
利用 += 來改變變數的值。
a = 1print aa += 1print aa += 2print a
得到的結果如下:
PS C:\python> python No20plus.py124
Python學習20:利用函數來列印檔案內容