**
在讀取檔案內容前需先開啟檔案,並且在結束後關閉檔案
若結束時沒有用close()關閉檔案,則會出現資料丟失或者安全問題。以移動檔案為例,沒有用close()關閉檔案,移動時系統會報錯說檔案在某處開啟無法移動**:
f =open
('hallo.txt'
,'r'
(f)f.close(
(f.read())
#read()函式將返回檔案內容
輸出:'hallo.txt' mode=
'r' encoding=
'cp936'
>
hallo
**用以上方法開啟檔案時會存在乙個問題:若在執行到close()函式前出現報錯,則close()不會執行,即檔案開啟了而沒有關閉,這時可以使用try finally
****:
try:
f =open
('hallo.txt'
,'r'
(f)print
(f.read())
finally
('false'
) f.close(
)返回:
false--
----
----
----
----
----
----
----
----
----
----
----
----
----
----
----
----
----
----
-filenotfounderror traceback (most recent call last)
input-11
-d15bdfc8a1de>
in1try:-
--->
2 f =
open
('hallo.txt'
,'r')3
(f)4
(f.read())
5 filenotfounderror:
[errno 2
] no such file
or directory:
'hallo.txt'
with as 和try finally一樣,但是它更加簡潔
with as原理:**:
with
open
('hallo.txt'
,'r'
)as f:
(f)print
(f.read())
返回:'hallo.txt' mode=
'r' encoding=
'cp936'
>
hallo
with將執行後後面的**,並將這部分**返回的值賦值給as後面的變數
比如:
with執行了open函式,並返回值賦值as後面的變數fwith
open
('hallo.txt'
,'r'
)as f:
python高階讀取檔案 Python讀取檔案內容
開啟檔案之後,就可以讀取檔案的內容,檔案物件提供多種讀取檔案內容的方法。開啟test.txt檔案 f open test.txt r 開啟test.txt檔案 f.close 關閉檔案 test.txt檔案有以下內容 hello world.hello python.hello imooc.讀取若干...
Python檔案讀取
python提供了多種方法實現檔案讀取操作 1 read 2 readline 3 readlines 4 xreadlines 很多人也在糾結到底應該選擇哪種方式,甚至疑問在處理大檔案時應該選擇哪種方式,因為擔心檔案過大導致記憶體佔用率過高甚至無法完全載入。其實,這個問題是多餘的,在引入了迭代器和...
python檔案讀取
1.讀取txt檔案 read 讀取整行檔案 readline 讀取一行資料 readines 讀取所有行的資料 讀取txt檔案 user file open user info.txt r lines user file.readlines forline inlines username line...