读取文件的几个方法
- 直接使用open函数
- 使用close函数关闭文件
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt','r')
print(f.read())
f.close()
- 使用try except方法
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt','r')
#print(f.read())
try:
data = f.read()
print(data)
except:
print('print error')
finally:
f.close()

问题总结:
- 以上方法每次读完文件以后都需要添加f.close() 来关闭文件
- 下面介绍如何使用with
with的使用
- 只用with以后就不需要使用f.close
with open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt','r') as f:
data = f.read()
print(data)
将with语句用于自定义的类
- enter , exit 只会被调用一次
class Mycall:
def __enter__(self):
print('__enter__() is call')
return self
def process1(self):
print('process1')
def process2(self):
print('process2')
def __exit__(self, exc_type, exc_val, exc_tb):
print('__exit__() is call')
print(f'type:{exc_type}')
print(f'value: {exc_val}')
print(f'trace: {exc_tb}')
with Mycall() as my:
my.process1()
my.process2()

总结
- with语句可以确保不管是否抛出异常,都会释放资源
2.如果with语句用于自定义类中,需要实现enter,exit方法,否则会抛出异常
加油 2020-3-8
网友评论