文件的操作
#1. 打开文件,得到文件句柄并赋值给一个变量
f=open(‘a.txt’,‘r’,encoding=‘utf-8’) #默认打开模式就为r
f是文件操作句柄
#2. 通过句柄对文件进行操作
data=f.read()
#3. 关闭文件
f.close()
whith 会自动关闭文件
with open(‘a.txt’,‘w’) as f:
pass
1.文件的读
1.r模式
r r+ rb
read() 全部读取
f1 = open(‘r模式’,encoding=‘utf-8’)
content = f1.read()
print(content,type(content))
f1.close()
read(n)
r模式: n 字符
rb模式: n 字节
f1 = open(‘r模式’,encoding=‘utf-8’)
print(f1.read(3))
f1.close()1
readline() 按行读取
f1 = open(‘r模式’,encoding=‘utf-8’)
print(f1.readline().strip()) # 读取第一行
print(f1.readline().strip()) # 读取第二行
f1.close()
readlines() 返回一个list 列表的每个元素是源文件的每一行
f1 = open(‘r模式’,encoding=‘utf-8’)
print(f1.readlines())
f1.close()
循环读取:使用文件操作句柄进行循环,防止文件过大,内存占用过大
f1 = open(‘r模式’,encoding=‘utf-8’)
for line in f1:
print(line)
f1.close()
3.r+ 读写模式:先读后写
f1 = open(‘r模式’,encoding=‘utf-8’,mode=‘r+’)
content = f1.read()
print(content)
f1.write(‘666’)
f1.close()
注意是限度后写,如果先写会替换内容
2.文件的写
w w+
1.w
没有文件,创建文件,写入内容,如果有文件,先清空内容,后写入
f = open(‘w模式’,encoding=‘utf-8’,mode=‘w’)
f.write(‘随便写一点’)
f.close()
2.w+
以二进制的形式写入
f1 = open(‘美女.jpg’,mode=‘r+’)
content = f1.read()
f1.close()
f2 = open(‘美女1.jpg’,mode=‘w+’)
f2.write(content)
f2.close()
3.文件的追加
a a+
1.a
没有文件,创建文件,写入内容,存在文件,会在后面追加内容
f = open(‘a模式’,encoding=‘utf-8’,mode=‘a’)
f.write(‘很多让人很有成就感的事情’)
f.write(‘很多让人很有成就感的事情’)
f.close()
深浅拷贝:copy
1.浅拷贝copy
同一代码块下:
l1 = [1, ‘泰山’, True, (1,2,3), [22, 33]]
l2 = l1.copy()
print(id(l1), id(l2)) # 2713214468360 2713214524680
print(id(l1[-2]), id(l2[-2])) # 2547618888008 2547618888008
print(id(l1[-1]),id(l2[-1])) # 2547620322952 2547620322952
不同代码块下:
l1 = [1, ‘泰山’, True, (1, 2, 3), [22, 33]]
l2 = l1.copy()
print(id(l1), id(l2))
1477183162120 1477183162696print(id(l1[-2]), id(l2[-2]))
1477181814032 1477181814032print(id(l1[-1]), id(l2[-1]))
1477183162504 1477183162504
深拷贝:
同一代码块下
import copy
l1 = [1, ‘alex’, True, (1,2,3), [22, 33]]
l2 = copy.deepcopy(l1)
print(id(l1), id(l2)) # 2788324482440 2788324483016
print(id(l1[0]),id(l2[0])) # 1470562768 1470562768
print(id(l1[-1]),id(l2[-1])) # 2788324482632 2788324482696
print(id(l1[-2]),id(l2[-2])) # 2788323047752 2788323047752
不同代码块下
import copy
l1 = [1, ‘泰山’, True, (1, 2, 3), [22, 33]]
l2 = copy.deepcopy(l1)
print(id(l1), id(l2))
1477183162824 1477183162632print(id(0), id(0))
1470562736 1470562736print(id(-2), id(-2))
1470562672 1470562672print(id(l1[-1]), id(l2[-1]))
1477183162120 1477183162312