Python文件打開方式(with語句)python
python編程中對於文件的打開方式主要有如下兩種:編程
一、利用直接性的open("","")函數:(舉例說明)函數
try:
import os
os.chdir("D:\\Study\\Python 練習\\") %找到所需打開文件的目錄
f=open("6-6.py","r")
for each in f:
print(each)
except OSError as reason:
print("出錯了"+str(reason))
finally:
f.close() %關閉文件spa
二、用with內置函數,它能夠將文件自動關閉,格式以下:3d
with open(「」,「」)as f:blog
對於1中以前的打開以下:it
try:
import os
os.chdir("D:\\Study\\Python 練習\\")
with open("6-6.py","r") as f:
for each in f:
print(each)
except OSError as reason:
print("出錯了"+str(reason))io