文件操作
1,文件路径
绝对路径:从根目录到目标文件路径
#绝对路径 f = open(‘d:\模特主妇护士班主任.txt‘,mode=‘r‘,encoding=‘UTF-8‘) content = f.read() print(content) f.close()
相对路径:根目录相同文件夹下的文件名
2,编码方式:utf-8,gbk.......
3,操作方式:只读,只写,追加,读写,写读.....
文件读取:以什么编码方式存储的就以什么编码方式打开
# f = open(‘文件路径‘,mode=‘r‘,encoding=‘UTF-8‘) # content = f.read() # print(content) # f.close()
只读:
r(Unicode类型) rb(bytes类型)
1,非文字类的文件用rd打开
2,上传 下载 储存文件用rb.
只写:w:没有此文件就会创建文件
#对于w:没有此文件就会创建文件 # f = open(‘log‘,mode=‘w‘,encoding=‘utf-8‘) # f.write(‘骑兵步兵‘) # f.close()
有文件,先将源文件的内容全部清除,再写
# 先将源文件的内容全部清除,在写。 # f = open(‘log‘,mode=‘w‘,encoding=‘utf-8‘) # f.write(‘附近看到类似纠纷‘) # f.close()
wb:
# f = open(‘log‘,mode=‘wb‘) # f.write(‘附近看到类似纠纷‘.encode(‘utf-8‘)) # f.close()
w+:
f = open(‘log‘,mode=‘w+‘,encoding=‘utf-8‘) # f.write(‘aaa‘) # f.seek(0) # print(f.read()) # f.close()
追加:
a:
# f = open(‘log‘,mode=‘a‘,encoding=‘utf-8‘) # f.write(‘佳琪‘) # f.close()
ab:
f = open(‘log‘,mode=‘ab‘) # f.write(‘佳琪‘.encode(‘utf-8‘)) # f.close()
a+:
f = open(‘log‘,mode=‘a+‘,encoding=‘utf-8‘) # f.write(‘佳琪‘) # f.seek(0) # print(f.read()) # f.close()
读写:
r+:
(r+b)bytes类型
# obj = open(‘log‘,mode=‘r+‘,encoding=‘utf-8‘) # content = f.read(3) # 读出来的都是字符 # f.seek(3) # 是按照字节定光标的位置 # f.tell() 告诉你光标的位置 # print(f.tell()) # content = f.read() # print(content) # f.tell() # f.readable() # 是否刻度 # line = f.readline() # 一行一行的读 # line = f.readlines() # 每一行当成列表中的一个元素,添加到list中 # f.truncate(4) # for line in f: # print(line) # f.close()
关键用法:
.read()读出来的是字符
.seek()按字节来找光标
.tell()告诉你光标的位置
.readline()一行一行的读
.readlines()每一行当成列表的一个元素添加到列表中
.truncate()截取一段来显示
编码方式:
bytes----->str decode 解码
str ------>bytes encode 编码
#str --->byte encode 编码 # s = ‘二哥‘ # b = s.encode(‘utf-8‘) # print(b) # #byte --->str decode 解码 # s1 = b.decode(‘utf-8‘) # print(s1)