Python的with语句(文件打开方式)

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

 

相关文章
相关标签/搜索