2020Python練習八——檔案處理3—b模式的檔案讀寫操作
@2020.3.16
#1、通用檔案copy工具實作
src_file=input('請輸入源檔案路徑>>: ').strip() dst_file=input('請輸入副本檔案保存路徑>>: ').strip() with open(r'{}'.format(src_file),mode='rb') as f1,\ open(r'{}'.format(dst_file),mode='wb') as f2: for line in f1: f2.write(line)
#2、基于seek控制指標移動,測驗r+、w+、a+模式下的讀寫內容
r(默認的操作模式):只讀模式,當檔案不存在時報錯,當檔案存在時檔案指標跳到開始位置
# r+ with open('user.txt',mode='r+b') as f1: print(f1.read()) f1.seek(0,0) # f1.write('Mili') #TypeError: a bytes-like object is required, not 'str' # f1.write(bytes('Mili')) #TypeError: string argument without an encoding f1.write(bytes('Mili',encoding='utf-8'))#此處將前四個字符改寫成Mili,此時指標在第5個字符的位置,即索引4 print(f1.tell()) print(f1.read()) #指標從第五個字符開始讀取剩余的字符 print(f1.tell())
b'MiliLoveYou'
4
b'LoveYou'
11
w:只寫模式,當檔案不存在時會創建空檔案,當檔案存在會清空檔案,指標位于開始位置
#user.txt——MiliLoveYou with open('user.txt',mode='w+b') as f2: f2.seek(0, 0) print(f2.read())# 此時檔案里面的內容已被清空 f2.write(bytes('CatsLoveYou',encoding='utf-8')) f2.seek(0, 0) print(f2.read())#新的內容CatsLoveYou寫入之前已被清空的檔案 f2.seek(4, 0) print(f2.tell())#tell()得到指標的位置 print(f2.read()) #指標從第五個字符開始讀取剩余的字符 print(f2.tell())
b'' b'CatsLoveYou' 4 b'LoveYou' 11
a:只追加寫,在檔案不存在時會創建空檔案,在檔案存在時檔案指標會直接調到末尾
# user.txt——CatsLoveYou with open('user.txt',mode='a+b') as f3: f3.seek(0, 0) print(f3.read())#讀取原內容 CatsLoveYou f3.write(bytes('MiliLoveYou',encoding='utf-8')) f3.seek(0, 0) print(f3.read())#在末尾添加新內容,最后輸出CatsLoveYouMiliLoveYou f3.seek(4, 0) print(f3.tell()) print(f3.read()) #指標從第五個字符開始讀取剩余的字符 print(f3.tell())
b'CatsLoveYouMiliLoveYou' b'CatsLoveYouMiliLoveYouMiliLoveYou' 4 b'LoveYouMiliLoveYouMiliLoveYou' 33
#3、tail -f access.log程式實作
tag = True while tag: cmd = input('請輸入命令:').strip() if cmd == 'tail -f access.log': with open(r'access.log', 'a+b') as f: #如果指令為tail -f access.log,沒有access.log檔案,a模式下則會新建該檔案,并將后面輸入的內容寫入檔案中 f.write(bytes('{}\n'.format(cmd), encoding='utf-8')) f.seek(0, 0) log = f.read().decode('utf-8') print(log) continue else: #如果指令不是tail -f access.log,則會持續要求輸入命令,直到指令為tail -f access.log # 才會創建access.log檔案,并將之前輸入的所有指令(包括tail -f access.log)寫入access.log with open(r'access.log', 'ab') as f: f.write(bytes('{}\n'.format(cmd), encoding='utf-8')) # 創建日志之后,日志還在要求 輸入命令,可繼續輸入內容 請輸入命令:貓愛米粒 請輸入命令:米粒愛貓 請輸入命令:來日方長,未來可期 請輸入命令:tail -f access.log 貓愛米粒 米粒愛貓 來日方長,未來可期 tail -f access.log 請輸入命令:
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/175709.html
標籤:Python
上一篇:Python踩坑記錄
