Python學習20:利用函數來列印檔案內容

來源:互聯網
上載者:User

標籤: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:利用函數來列印檔案內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.