1. 程式人生 > >文件處理

文件處理

log utf-8 writable ren 是否 文件 pan tell 其他

#r模式,默認模式,文件不存在則報錯
# f=open(‘a.txt‘,encoding=‘utf-8‘)
# print(f.read())#讀全部
# print(f.readline())#讀一行
# print(f.readlines())#讀全部列表形式
# f.close()#關閉
#w模式,沒有文件則創建一個新文件,存在則覆蓋
# f=open(‘b.txt‘,‘w‘,encoding=‘utf-8‘)
# f.write()
# f.writelines()#以列表為單位往裏面寫
# f.close()
#a模式,沒有文件則一個新文件,文件存在不會覆蓋,寫內容是追加的方式寫
# f=open(‘c.txt‘,‘a‘,encoding=‘utf-8‘) # f.write() # f.close() #其他方法 #a模式,沒有文件則一個新文件,文件存在不會覆蓋,寫內容是追加的方式寫 # f=open(‘a.txt‘,‘w‘,encoding=‘utf-8‘) # f.write() # f.flush()#把內存數據刷到硬盤 # f.close() # print(f.closed)#判斷文件是否關閉 # print(f.name,f.encoding)#查看文件名和字符編碼 # print(f.readable())#判斷是否可讀 #
print(f.writable())#判斷是否可寫 # f=open(‘a.txt‘,encoding=‘utf-8‘) # print(f.read(3))#讀取三個字符 # f.seek(0)#移動光標到開始位置 # f.seek(3)#從文件開頭移動三個字節 # print(f.tell())#打印當前光標的位置 # print(f.truncate(3))#截斷文件開始的3個字節 # f.close()#關閉 # rb # f=open(‘a.txt‘,‘rb‘) # f.seek(3,0)#默認是0,從文件開頭移動3個字節 # f.seek(3,1)#從當前位置開始移動3個字節
# f.seek(-1,2)#從末尾開始移動3個字節 # print(f.read())#二進制的形式 # print(f.read().decode(‘utf-8‘))#bytes轉unicode # f.close() # wb # f=open(‘d.txt‘,‘wb‘) # print(f.write()) # print(‘wahaha‘.encode(‘utf-8‘))#unicode轉bytes # f.close() #修改文件 # import os # read_f=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘) # write_f=open(‘a.txt.swp‘,‘w‘,encoding=‘utf-8‘) # for line in read_f: # if ‘wa‘ in line: # line=line.replace(‘wa‘,‘ha‘) # write_f.write(line) # read_f.close() # write_f.close() # os.remove(‘a.txt‘) # os.rename(‘a.txt.swp‘,‘a.txt‘) #上下文管理with # import os # with open(‘a.txt‘,‘r‘,encoding=‘utf-8‘) as read_f,\ # open(‘a.txt.swp‘,‘w‘,encoding=‘utf-8‘) as write_f: # for line in read_f: # if ‘wa‘ in line: # line=line.replace(‘wa‘,‘ha‘) # write_f.write(line) # os.remove(‘a.txt‘) # os.rename(‘a.txt.swp‘,‘a.txt‘)

文件處理