python 文件讀取

  • 讀取整個文件
    操作文件的第一步就是得打開要操作的文件,然後進行讀取。在python中我們可以使用open函數來打開一個文件,然後使用read方法來讀取文件。

示例:

import os

with open('data.txt', encoding='utf-8') as file_obj:
    contents = file_obj.read()
    print(contents.rstrip())

首先,我們看下open函數的定義:

def open(file: Union[str, bytes, int], mode: str = ..., buffering: int = ..., encoding: Optional[str] = ...,              errors: Optional[str] = ..., newline: Optional[str] = ..., closefd: bool = ...) Inferred type: (file: Union[str, bytes, int], mode: str, buffering: int, encoding: Optional[str], errors: Optional[str], newline: Optional[str], closefd: bool) -> IO Open file and return a stream. Raise IOError upon failure. 

在一般情況下,我們打開文件只需要傳入文件路徑即可,這裏我們讀取的文件的內容是中文,爲了避免亂碼,我們在這裏指定了編碼格式。其他的參數等我們用到的時候,在仔細說明。

open函數返回一個表示文件的對象,python會將這個對象存儲在我們的變量file_obj中,這樣我們就可以方便的操作了。

data.txt和我們的文件在同一目錄下,所以直接使用名稱即可:
這裏寫圖片描述

如果是其他路徑(非程序目錄),那麼直接使用絕對路徑:
我是在window的開發環境,以windows爲例:

file_path = 'D:\data.txt'
with open(file_path, encoding='utf-8') as file_obj:

read()方法讀取文件的整個內容,並將其作爲字符串返回。

其他的我們先不做說明,先來看下文件運行結果,是否將文件內容成功讀取:
這裏寫圖片描述

雖然我們的文本有點多,大家可以仔細看一下,就當回味一下高中生活了。

有些仔細一點的朋友可能發現了,這裏我們只是使用了open和read來打開和讀取文本文件,但是並沒有關閉文件句柄,這一點有點奇怪,我們在其他的語言open和close總是成雙成對的出現的。

這裏的奧妙就在於with關鍵字,使用該關鍵字可以讓python去確定,我們在不需要訪問文件的時候自動關閉文件。也就是說我們只需要打開和操縱文件,python會在合適的機會關閉文件。

我們在將文件打開後,打印一下這個file_obj到底有些什麼:

 print(dir(file_obj))

輸出:

['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '_
_init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable',
 '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline',
'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']

這些都是和文件操作相關的,在這裏不會給大家做仔細說明,只是讓大家對這些東西有個印象,等遇到了,我們在說怎麼使用。

  • 逐行讀取
    上面是讀取整個文件內容,接下來我們看下怎麼逐行讀取文件,爲了方便演示,我們將data的內容修改爲幾行數字。

在逐行讀取文本的時候,常見的可以使用for循環來讀取:

with open(file_path, encoding='utf-8') as file_obj:
    for line in file_obj:
        print(line)

還有就是使用readline方法來逐行讀取文件:

with open(file_path, encoding='utf-8') as file_obj:
    line = file_obj.readline()
    while line != '':
        print(line)
        line = file_obj.readline()

另外一種倒像是第二種的升級版,它會一次性的將文件逐行讀取存入一個列表中,一遍我們使用:

with open(file_path, encoding='utf-8') as file_obj:
    lines = file_obj.readlines()

for line in lines:
    print(line)

lines 在代碼塊with之外也是可以使用的。

說了幾種常見的使用方法,我們來看下程序運行輸出:

D:\Programs\python\HelloWorld\venv\Scripts\python.exe D:\Programs\python\HelloWorld\python_file.py
1234

2345

3456

4567


Process finished with exit code 0

大家可以看到,我們讀取的數據沒有任何問題,但是每行數據之間都會存在多餘的空行,這是因爲在文件中每行的末尾都會有一個看不見的換行符。如果我們希望去除這些多餘空行,可以使用rstrip()函數:

def rstrip(self, chars: Optional[str] = ...) Inferred type: (self: str, chars: Optional[str]) -> str 
S.rstrip([chars]) -> str
Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead.

那麼上面的例子我們該這麼修改:

with open(file_path, encoding='utf-8') as file_obj:
    lines = file_obj.readlines()

for line in lines:
    print(line.rstrip())

輸出:

1234
2345
3456
4567
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章