[Python學習20] 利用函數來打印文件內容

# -- 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."

# 使用上面自定義的函數rewind
rewind(current_file)

print "Let's print three lines:"

# 定義一個變量,每打印完一行就加1,把這個變量作爲print_a_line函數的參數,調用print_a_line函數可以依次打印每一行。
# 下面的幾行代碼可以採用循環來寫,以減少代碼長度。
current_line = 1
print "Now Current line is : %d" % current_line
print_a_line(current_line, current_file)

current_line = current_line + 1
print "Now Current line is : %d" % current_line
print_a_line(current_line, current_file)

current_line = current_line + 1
print "Now Current line is : %d" % current_line
print_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.
參數偏移是一個字節數。
可選參數從默認值爲0(從文件開始時偏移,偏移量應該是大於0);
其他值:
1(表示移動相對於當前位置,正或負)
2(表示移動到文件末尾,通常是負的,儘管許多平臺允許在文件的末尾進行搜索)。
如果文件是在文本模式下打開的,那麼由tell()函數返回的偏移量是合法的。
使用其他偏移量會導致未定義的行爲。
注意,並不是所有的文件對象都是可看到的。
利用 += 來改變變量的值。

a = 1
print a
a += 1
print a
a += 2
print a

得到的結果如下:

PS C:\python> python No20plus.py
1
2
4
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章