Python文件打开方式(with语句)
python编程中对于文件的打开方式主要有以下两种:
1、利用直接性的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() %关闭文件
2、用with内置函数,它可以将文件自动关闭,格式如下:
with open(“”,“”)as f:
对于1中之前的打开如下:
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))