1.with语句
#open()方式打开文件的弊端.
f = open('1.txt','w')
f.write('hello world')
f.flush()
# f.close() == 不释放资源--其它人无法操作被占用的文件.
#-------------发生异常导致没有释放资源---------
# f = open('1.txt','r')
# f.write('hello world')
# f.flush()
# f.close()
# 可以释放资源---但是格式复杂---麻烦!!!
f = None
try:
f = open('1.txt','r')
f.write('hello world')
f.flush()
except Exception as e:
print('出错误了')
finally:
if f is not None:
f.close()
while True:
pass
with open("1.txt",'w') as f:
f.write('hello\n')
f.write('world\n')
f.write('python\n')
# f.close() # 使用with语句后.能帮我们自动释放资源.
while True:
pass
2.深拷贝和浅拷贝
# 语法: 1.导入模块 copy
import copy
# 不可变类型有: 数字、字符串、元组
# a1 = 123
# b1 = copy.copy(a1)
# print(id(a1))#2697886781688
# print(id(b1))#2697886781688
#
# b2 = a1
# print(id(a1))#2697886781688
# print(id(b2))#2697886781688
# a2 = 'abc'
# b2 = copy.copy(a2)
# print(id(a2))#2697886781168
# print(id(b2))#2697886781168
# a3 = (1,2,[3,4])
# b3 = copy.copy(a3)
# print(id(a3))#2165171410048
# print(id(b3))#2165171410048
# print(id(a3[2]))#2272505786496
# print(id(b3[2]))#2272505786496
# 可变类型有: 列表、字典、集合
# a4 = [1,2,3]
# b4 = copy.copy(a4)
# print(id(a4))#2281864200256
# print(id(b4))#2281863566720
# a5 = {"name":"tom","age":20}
# b5 = copy.copy(a5)
# print(id(a5))#1807425866112
# print(id(b5))#1807425866176
# a6 = {1,2,3}
# b6 = copy.copy(a6)
# print(id(a6))#2784928707520
# print(id(b6))#2784928707744
a7 = [1,2,[3,4]]
b7 = copy.copy(a7)
print(id(a7))#2081913886016
print(id(b7))#2081913871360
#如果使用浅拷贝拷贝列表中的可变元素.该元素不会被重新创建对象.
print(id(a7[2]))#2153571123328
print(id(b7[2]))#2153571123328
a7[2][0] = 9
print(a7)#[1,2,[9,4]]