with
with是一种上下文管理协议,目的是从流程图中把try,except和finally关键字以及资源分配释放相关代码统统去掉,简化try-excepet-finally的处理流程
with确保了不管过程中是否发生异常都会执行必要的清理,释放资源,例如:文件使用后自动关闭等
1.语法格式
with expression [as target]:
.....
2.用法探究
学习自博客:
https://www.cnblogs.com/wwbplus/p/11329541.html
import numpy as np
import os
获取当前文件的目录
current_path=os.getcwd()
print(current_path)
#path1=os.path.abspath(__file__) #注意了,__file__只有在脚本程序中才会有定义,在终端或交互式中是没有定
获取当前文件的路径
path2=os.path.dirname(os.path.abspath(__file__)) #包含了当前脚本的文件名
a=np.array([1,2])
np.save(current_path+'/a.npy',a)
**使用with打开a.npy**
a=np.load(current_path+'/a.npy')
with np.load(current_path+'/a.npy') as np_load: #没有这种用法哦!,with只能打开txt文件,那么下面换成txt试试喽
print(np_load())
np.savetxt(current_path+'/a.txt',a)
with open(current_path+'/a.txt') as fp: #整个文件的读取
print(fp.read())
输出:
1.000000000000000000e+00
2.000000000000000000e+00
with open(current_path+'/a.txt') as fp: #整个文件的读取
print(fp.readline())
print(fp.readlines()) #读取下一行,但是输出的是列表
print(fp.readlines()) #输出空列表
print(fp.readline()) #没有能输出的了
输出:
1.000000000000000000e+00
['2.000000000000000000e+00\n']
[]
b=np.array([[1,2],[3,4]])
np.savetxt(current_path+'/b.txt',b)
with open(current_path+'/b.txt'),open(current_path+'/a.txt') as fp,\
open(current_path+'/b.txt','w') as fw: #with里面输入再多的open也只会执行最后一个open
fw.write('aaaa')
print(fp.read())
输出:
1.000000000000000000e+00
2.000000000000000000e+00
with open(current_path+'/b.txt') as fp: #测试b.txt是否已经被全部修改了
print(fp.read())
输出:
aaaa
with open(current_path+'/a.txt') as fp, open(current_path+'/b.txt') as fp2:
for i in fp: #可以用for的形式来替换掉.readline()
print(i)
print(fp2.readline())
输出:
1.000000000000000000e+00
aaaa
2.000000000000000000e+00
with open(current_path+'/b.txt') as fp2:
for i in fp2: #可以用for的形式来替换掉.readline()
print(i)
输出:
aaaa
3.在TensorFlow中的应用
不使用with的 Session
import tensorflow as tf
a = tf.constant([1.0, 2.0])
b = tf.constant([3.0, 4.0])
c = a * b #点乘
sess = tf.Session() #创建会话
print(sess.run(c))
sess.close() #手动关闭会话
输出:
[3. 8.]
使用with的 Session
import tensorflow as tf
a = tf.constant([1.0, 2.0])
b = tf.constant([3.0, 4.0])
c = a * b
with tf.Session() as sess: #使用with就可以不同手动关闭会话了
print(sess.run(c))
输出:
[3. 8.]
补:Tensorflow gpu/cpu的指定配置
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
import time
import tensorflow as tf
for d in ['/device:CPU:0','/device:GPU:0']: #用cpu和gpu分别测试了速度
with tf.device(d):
start=time.time()
a=tf.constant([1.0,2.0,3.0,4.0,5.0,6.0],shape=[2,3])
b=tf.constant([1.0,2.0,3.0,4.0,5.0,6.0],shape=[3,2])
c=tf.matmul(a,b)
end=time.time()
consuming_time=tf.convert_to_tensor(end-start) #必须要转成tensor变量
sess=tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(sum))
print(sess.run(consuming_time))
本人现在的研究方向是:
图像的语义分割,如果有志同道合的朋友,可以组队学习
haiyangpengai@gmail.com qq:1355365561