從檔案輸入

也可以從檔案中讀取輸入。可以使用內建函式 open 開啟檔案。使用 with <command> as <name> 語法(稱為上下文管理器)使得使用 open 並獲得檔案的控制代碼非常容易:

with open('somefile.txt', 'r') as fileobj:
    # write code here using fileobj

這可確保在程式碼執行離開塊時檔案自動關閉。

檔案可以以不同的模式開啟。在上面的示例中,檔案以只讀方式開啟。要開啟現有檔案以供閱讀,請使用 r。如果要將該檔案作為位元組讀取,請使用 rb。要將資料附加到現有檔案,請使用 a。使用 w 建立檔案或覆蓋任何同名的現有檔案。你可以使用 r+開啟檔案進行讀寫。open() 的第一個引數是檔名,第二個是模式。如果模式為空白,則預設為 r

# let's create an example file:
with open('shoppinglist.txt', 'w') as fileobj:
    fileobj.write('tomato\npasta\ngarlic')

with open('shoppinglist.txt', 'r') as fileobj:
    # this method makes a list where each line 
    # of the file is an element in the list
    lines = fileobj.readlines()

print(lines)
# ['tomato\n', 'pasta\n', 'garlic']

with open('shoppinglist.txt', 'r') as fileobj:
    # here we read the whole content into one string:
    content = fileobj.read()
    # get a list of lines, just like int the previous example:
    lines = content.split('\n')

print(lines)
# ['tomato', 'pasta', 'garlic']

如果檔案的大小很小,則可以安全地將整個檔案內容讀入記憶體。如果檔案非常大,通常最好逐行或按塊讀取,並在同一迴圈中處理輸入。要做到這一點:

with open('shoppinglist.txt', 'r') as fileobj:
    # this method reads line by line:
    lines = []
    for line in fileobj:
        lines.append(line.strip())

讀取檔案時,請注意特定於作業系統的換行符。雖然 for line in fileobj 會自動將它們剝離,但在讀取的行上呼叫 strip() 總是安全的,如上圖所示。

開啟的檔案(上例中的 fileobj)始終指向檔案中的特定位置。首次開啟它們時,檔案控制代碼指向檔案的最開頭,即 0 的位置。檔案控制代碼可以用 tell 顯示它的當前位置:

fileobj = open('shoppinglist.txt', 'r')
pos = fileobj.tell()
print('We are at %u.' % pos) # We are at 0.

在讀取所有內容後,檔案處理程式的位置將指向檔案的末尾:

content = fileobj.read()
end = fileobj.tell()
print('This file was %u characters long.' % end)
# This file was 22 characters long.
fileobj.close()

檔案處理程式位置可以設定為所需的任何位置:

fileobj = open('shoppinglist.txt', 'r')
fileobj.seek(7)
pos = fileobj.tell()
print('We are at character #%u.' % pos)

你還可以在給定呼叫期間從檔案內容中讀取任何長度。為此,傳遞 read() 的引數。當沒有引數呼叫 read() 時,它將一直讀到檔案結尾。如果傳遞引數,它將讀取該位元組數或字元數,具體取決於模式(分別為 rbr):

# reads the next 4 characters 
# starting at the current position
next4 = fileobj.read(4)
# what we got?
print(next4) # 'cucu'
# where we are now?
pos = fileobj.tell()
print('We are at %u.' % pos) # We are at 11, as we was at 7, and read 4 chars.

fileobj.close()

要演示字元和位元組之間的區別:

with open('shoppinglist.txt', 'r') as fileobj:
    print(type(fileobj.read())) # <class 'str'>

with open('shoppinglist.txt', 'rb') as fileobj:
    print(type(fileobj.read())) # <class 'bytes'>