with上下文管理可以自動管理資源,在with代碼塊執行完畢後自動還原進入該代碼之前的現場或上下文。不論何種原因跳出with塊都能保證文件正確的關閉。
使用try...finally關閉文件流
try:
f=open("d:/a.txt","r")
content=f.readline()
print(content)
except:
print("文件未找到")
finally:
print("run in finally.關閉資源")
try:
f.close()
except BaseException as e:
print(e)
使用with關鍵字
with open("d:/a.txt","r") as f:
content=f.readline()
print(content)
print("程序執行結束!")
讀取一個文件前四個字符
with open(r"bb","r",encoding="utf-8") as f:
print(f.read(4))
文件較小,一次將文件內容讀到程序中
with open(r"d:\bb.txt","r") as f:
print(f.read())
按行讀取一個文件
with open(r"bb","r") as f:
while True:
fragment=f.readline()
if not fragment:
break
else:
print(fragment,end="")
使用迭代器 (每次返回一行)讀取文本文件
with open(r"d:\bb.txt","r") as f:
for a in f:
print(a,end="")