一 初識文件操做python
使⽤用python來讀寫⽂文件是很是簡單的操做. 咱們使⽤用open()函數來打開⼀一個⽂文件, 獲取到⽂文
件句句柄. 而後經過⽂文件句句柄就能夠進⾏行行各類各樣的操做了了. 根據打開⽅方式的不一樣可以執⾏行行的操
做也會有相應的差別.
打開⽂文件的⽅方式: r, w, a, r+, w+, a+, rb, wb, ab, r+b, w+b, a+b 默認使⽤用的是r(只讀)模式app
二 函數
讀 1. " r " spa
f=open("e:/課堂練習.txt",mode="r",encoding="GBK")
for line in f:
print(line)
f.close() #關閉
f是一個可迭代對象 f = open("d:/周潤發大戰奧特曼.txt", mode="r", encoding="utf-8") # 默認跟着操做系統走的 GBK # for line in f: # 內部其實調用的是readline() # print(line) # f.close() # 關閉
寫 2." w " 操作系統
f = open("d:/sylar.txt", mode="w", encoding="utf-8") f.write("周筆暢\n") # 第一次寫的時候. 先清空. 再寫入. 繼續寫不會清空了 f.write("胡辣湯") f.write("實付款\n") f.flush() # 必須加 f.close() #最後這個
追加 a日誌
f = open("d:/sylar.txt", mode="a", encoding="utf-8") f.write("娃哈哈") # 追加寫 f.write("爽歪歪") f.flush() f.close()
r+ 讀寫code
f = open("菜單", mode="r+", encoding="utf-8") # r+最多見 s = f.read(1) # 讀取一個字符 print(s) f.write("胡辣湯") # r+模式. 若是你執行讀了操做. 那麼寫操做的時候. 都是寫在文件的末尾. 和光標沒有關係 # f.write("ab") # 在文件開頭寫入. 寫入的是字節,把原來的內容蓋上 # for line in f: # print(line) # f.write("蛋炒飯") # 正確用法: 先讀後寫 f.close()
w+ x寫讀對象
f = open("菜單", mode="w+", encoding="utf-8") # 不多用. f.write("疙瘩湯") f.seek(0) # 移動到開頭 content = f.read() print("讀取的內容是", content) f.flush() f.close()
a+ 追加讀blog
f = open("菜單", mode="a+", encoding="utf-8") f.write("韭菜雞蛋餃子") f.seek(0) content = f.read() # print(content)
三 光標 ip
使用tell()能夠知道光標在哪裏
# seek()能夠移動光標
# 讀寫的時候. 單位 字符
# 光標: 單位是字節
# 光標移動到末尾: seek(0,2)
seek(偏移量, 位置)
# 位置: 0開頭, 1當前位置, 2末尾
# 移動到末尾: seek(0, 2)
2.截斷
f = open("個人天吶", mode="r+", encoding="utf-8") f.seek(9) f.truncate(12) # 若是沒有參數. 按照光標來截斷. 若是有參數. 截斷到參數位置 f.flush() f.close()
3.修改文件
mport os # 引入os模塊 with open("alex", mode="r", encoding="utf-8") as f1, \ open("alex_副本", mode="w", encoding="utf-8") as f2: for line in f1: new_line = line.replace("good", "sb") f2.write(new_line) os.remove("alex") os.rename("alex_副本", "alex")
4.日誌處理
result = [] with open("2018-09-12.log", mode="r", encoding="utf-8") as f: hang = f.readline() title = hang.split("|") for line in f: line = line.strip() # 去掉空白, 2018-09-11 00:00:01|劉偉|吃雞 lst = line.split("|") dic = {title[0]: lst[0], title[1]: lst[1], title[2]: lst[2]} result.append(dic) print(result)