1.读取文件
f=open('text','r',encoding='utf8');#读文件
data=f.readlines();
for i in data:#遍历文件内容
print(i);
f.close();
2.写入
f=open('text','w',encoding='utf8');#写入文件参数1文件名,没有则创建参数2w代表write,参数3代表字符编码
f=open('text','a',encoding='utf8');#写入文件参数1文件名,没有则创建参数2a代表append,参数3代表字符编码
f.write('c');#当模式为w时覆盖原来文件 ,当模式为a时往后面添加。
f.close();
3.光标
f=open('text','r',encoding='utf8');#文件读
print(f.tell());#光标的位置,中文默认为3个字符
print(f.read(3));
print(f.tell()) ;
f.seek(0);#调整光标位置
f.close();
4.flush文件刷新,实现进度条
import sys,time
for i in range(20):
sys.stdout.write("*");
sys.stdout.flush();
time.sleep(1);
5.truncate方法截断
f=open('text','a',encoding='utf8');
f.truncate(2) #当文件模式为w时清空所有文件后移动光标,模式为a时截断
6.with关闭文件流
with open ('test') as f
f.write('111');