文件操作with語句

import sys

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)
count+=1
'''

#光標使用

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("gc.txt",'w+',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) #執行完自動關閉文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章