文件相关的操作
打开文件: r read 读取 w write 覆盖写 a append 追加写 r+ 读写 w+ 写读 a+ 可追加可读 编码方式一般utf-8
操作文件: -读 read 一次性 readlines 一次性读 readline 一行行读取 视频 图片 音频 rb wb 操作bytes 最好的for循环方式 -写 write -光标 seek:指定光标移动到某个位置 tell: 获取当前光标的位置 turncate: 截取文件
# 文件修改 把原来的文件读到python,python再创建一个新文件,把内容放到这个新文件里面,再删除之前的文件,达到修改的目的 with open('小花','r',encoding='utf-8') as f1,open('小花.bak','w',encoding='utf-8') as f2: for line in f1: if '哈哈哈' in line: line = line.replace('哈哈哈','开心点') #替换str f2.write(line) import os os.remove('小花') #删原文件 os.rename('小花.bak','小花') #重命名