常用文件处理函数
1. with open(r'a.txt',mode='rb') as f:
res=f.read() #一次性读取整个文件内容到内存
print(res,type(res))
2. with open(r'a.txt',mode='rb') as f:
res=f.readline() #一次读取一行到内存中
print(res,type(res))
3. with open(r'a.txt',mode='rb') as f:
res=f.readlines() #循环读取,存入列表中,每行值是列表中的元素
print(res,type(res))
------------------------------------------------------------------------------
4. with open(r'a.txt',mode='wb') as f:
f.write("faifjaif\nfjioajf".encode("utf-8")) #写入一行内容到文件中
5. with open(r'a.txt',mode='wb') as f:
res=f.writable() #文件是否可写,返回的是布尔值
print(res,type(res))
6. with open(r'a.txt',mode='wb') as f:
f.writelines(['fadfa\n'.encode('utf-8'),'fafafa'.encode('utf-8')]) #将列表中德元素写入到文件中
seek控制指针移动
seek的三种模式:0(相对于文本开头发生的位移),1(相对于当前位置发生的位移),2(相对于文本末尾发生的位移)
seek默认的移动单位为字节;一个字节表示一个英文字符;三个字节表示一个汉字;
with open(r'a.txt',mode='rt',encoding='utf-8') as f:
f.seek(6,0) #0代表的是seek的模式,6代表指针向后移动6个字节
res=f.read()
print(res)