說說在 Python 中,如何讀取檔案中的資料

deniro發表於2019-04-13

說說在 Python 中,如何讀取檔案中的資料

1 一次性讀取

我們想要讀取《傲慢與偏見》txt 小說(為簡化例子,我們的 txt 只包含一段文字):

file = 'novel.txt'
with open(file) as file_object:
    contents = file_object.read()
    print(contents)
複製程式碼

執行結果:

It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.

要使用檔案,就必須先開啟它,所以這裡使用了函式 open() 。該函式 open() 接受一個引數: 即要開啟的檔案路徑。 如果只有檔名,那麼 Python 會在當前執行檔案的所在目錄來查詢指定的檔案。

關鍵字 with 會在程式不再需要訪問檔案或出現異常的情況下,關閉檔案 。 我們只管開啟檔案使用它即可,Python 是不是很貼心哦O(∩_∩)O~

2 檔案路徑

函式 open(),入參如果只有檔名,那麼 Python 會在當前執行的 .py 檔案的所在目錄中,查詢檔案 。

也可以提供檔案路徑 , 讓 Python 到指定的檔案目錄中去查詢所需要的檔案。

相對路徑語法形如:

with open('xxx\novel.txt') as file_object:
複製程式碼

一般來說,在 Windows 系統中, 在檔案路徑中使用反斜槓( \ ) ,Linux 與 OS 使用的是是斜槓( / ) 。實際測試,在 Windows 7+ 系統中,斜槓與反斜槓都支援。

當然,也可以使用絕對路徑。注意: 如果使用的是絕對路徑,那麼在 Windows 7+ 系統中,檔案路徑必須使用反斜槓。形如:

with open('F:/python_projects/xxx/novel.txt') as file_object:
複製程式碼

因為絕對路徑一般較長, 所以一般將其儲存在變數中,然後再傳入 open() 函式。

3 逐行讀取

可以對檔案物件使用 for 迴圈,逐行讀取檔案內容。

with open(file) as file_object:
    for line_content in file_object:
        print(line_content.rstrip())
複製程式碼

執行結果與之前的 “一次性讀取” 示例結果相同。在 txt 檔案中, 每行的末尾都存在一個看不見的換行符。消除為了去除這些多餘的空白行,我們使用了 rstrip() 函式。rstrip() 函式會刪除 string 字串末尾的空格。

4 在 with 外訪問

使用關鍵字 with 時, open() 函式所返回的檔案物件,只能在 with 程式碼塊中使用 。 如果需要在 with 程式碼塊之外,訪問檔案的內容, 那麼可以在 with 程式碼塊之內,將檔案中的各行內容儲存在列表變數中,然後就可以在 with 程式碼塊之外,通過該列表變數,來訪問檔案內容啦O(∩_∩)O~

with open(file) as file_object:
    contents = file_object.readlines()

content_str=''
for content in contents:
    content_str+=content
print('content_str='+content_str)
print('len='+str(len(content_str)))
複製程式碼

執行結果:

content_str=It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife. len=117

注意: 讀取文字檔案時, Python 會將檔案中的所有文字都解釋為字串 。 如果我們需要將其中的文字解釋為數字,那麼就必須使用函式 int() 或者 float(),將其轉換為整數或者浮點數。

Python 對資料量沒有大小限制, 只要我們的系統記憶體足夠多O(∩_∩)O~

相關文章