python文件操作
文件操作
打开文件
=需要指定编码=============
用于读取给用户看的
open(file_path,mode='r',encoding='utf-8') # 字符方式读取
open(file_path,mode='w',encoding='utf-8') # 存在源文件则覆盖,不存在则新建
open(file_path,mode='a',encoding='utf-8') # 在源文件末尾追加,不存在则新建
=不需要指定编码===========
不需要读取给用户看的,在后台操作的时候可使用
如果需要读取给用户看,则需:将读取的数据encode转码
open(file_path,mode='rb') # 字节方式读取
open(file_path,mode='wb') # 字节方式写入
open(file_path,mode='ab') # 字节方式追加
注:
file_path格式:r'file_path' 去除特殊转义格式
读写文件
读
f.read() 默认读取全部内容
f.read(n) 读取n个字符(r方式打开)或字节(rb方式打开)用于处理大文件
f.readline() 一行一行的读取,不知道什么时候结束
for line in f: 一行一行读,不占内存,又可读到最后自动停
写
f.write('str')
f.write(b'str')
关闭文件
f.close()
with open(r'file_path', mode=r'r',encoding='utf-8') as f:
# 该方式文件操作,不要使用close手动关闭!
删除和修改
import os
os.remove(r'file_path') 删除文件
os.rename(r'file_path') 重命名
修改文件:
读a文件,写b文件
删除a,重命名b->a
文件指针
f.tell() # 查看当前文件指针所在的位置
f.seek(0) # 修改文件指针位置到起始位置
浙公网安备 33010602011771号