python基礎學習-檔案讀寫
阿新 • • 發佈:2018-12-15
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');