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~