文件操作with語句
data=open("gc.txt","r",encoding="utf-8") #只能讀取文件
data=open("gc.txt","w",encoding="utf-8") #寫模式創建一個文件(如果文件名相同會覆蓋掉)
data=open("gc.txt","a",encoding="utf-8") #只能在文件後面追加
print(data.readline()) #打印一行
print(data.readlines()) #打印成列表
for i in range(5):
print(data.readline())
‘‘‘
#low 方法 適合讀小文件
for index,line in enumerate(data.readlines()):#取出下標和對應的值
if index==9:
print("----ooo----")
continue
print(line.strip())
#high bige 度一行覆蓋一行,常用牛逼方法
count=0
for loo in data:
if count==4:
print(‘-----You will die-----‘)
count+=1
continue
print(loo)
‘‘‘
#光標使用
f=open("gc.txt","r",encoding="utf-8")
print(f.tell())#打印光標當前位置
print(f.read(5))
print(f.readline())
print(f.tell())
f.seek(0)#光標移動端指定位置
print(f.encoding)#打印所用字符編碼
print(f.flush())#強制刷新
f.truncate(10)#截斷,從開頭開始截,光標移動後再截斷沒用,依然從頭開始算。
#f=open("yesok2",‘r+‘,encoding="utf-8")#文件句柄 讀寫,在最後追加
#f=open("yesok2",‘a+‘,encoding="utf-8")#文件句柄 追加讀寫
f=open("yesok2",‘rb‘) #文件句柄 以二進制讀文件
f=open("yesok2",‘wb‘) #文件句柄 以二進制寫
f=open("yesok2",‘ab‘) #文件句柄 以二進制追加
f.write("hello\n".encode()) #二進制寫讀
f.close
f=open("gc.txt","r",encoding="utf-8")
f1=open("gc1.txt","w",encoding="utf-8")
for line in f:
if "是掙紮的自由" in line:
line=line.replace("是掙紮的自由","有我無敵天下")
f1.write(line )
#f.close()
#f1.close()
#find_str=sys.argv[1]
#replace_str=sys.argv[2]
#for line in f:
#if find_str in line:
#line=line.replace(find_str,replace_str)
#f1.write(line)
#f.close()
#f1.close()
with語句
with open("gege",‘r‘,encoding="utf-8") as f:
for line in f:
print(line) #執行完自動關閉文件
同時打開文件不建議這麽寫
with open("gege",‘r‘,encoding="utf-8") as f,open("gege",‘r‘,encoding="utf-8") as f:
pass
打開多個文件建議這麽寫
with open("gege",‘r‘,encoding="utf-8") as f,\
open("gege",‘r‘,encoding="utf-8") as f2:
for line in f:
print(line) #執行完自動關閉文件
文件操作with語句