可能有的時候有人會在想爲何要對文件進行操做,不管對於文件仍是網絡之間的交互,咱們都是創建在數據之上的,若是咱們沒有數據,那麼不少的事情也就不可以成立,好比咱們淘寶買了一件衣服,那麼淘寶是如何知道咱們的相關信息的呢?爲何不會把咱們的衣服發給別人呢?這些都基於咱們自己的數據。而咱們的數據通常都存放在哪呢?python
在咱們沒有接觸數據庫以前,咱們得到數據的手段也只能是從文件中獲取,所以Python中的文件操做也是十分的重要。linux
操做文件時,通常須要經歷以下步驟數據庫
read() , 所有讀到內存windows
read(1)網絡
1表示一個字符code
obj = open('a.txt',mode='r',encoding='utf-8') data = obj.read(1) # 1個字符 obj.close() print(data)
1表示一個字節內存
obj = open('a.txt',mode='rb') data = obj.read(3) # 1個字節 obj.close()
write(字符串)utf-8
obj = open('a.txt',mode='w',encoding='utf-8') obj.write('中午你') obj.close()
write(二進制)資源
obj = open('a.txt',mode='wb') # obj.write('中午你'.encode('utf-8')) v = '中午你'.encode('utf-8') obj.write(v) obj.close()
seek(光標字節位置),不管模式是否帶b,都是按照字節進行處理。字符串
obj = open('a.txt',mode='r',encoding='utf-8') obj.seek(3) # 跳轉到指定字節位置 data = obj.read() obj.close() print(data) # rb模式 obj = open('a.txt',mode='rb') obj.seek(3) # 跳轉到指定字節位置 data = obj.read() obj.close() print(data)
tell(), 獲取光標當前所在的字節位置
obj = open('a.txt',mode='rb') # obj.seek(3) # 跳轉到指定字節位置 obj.read() data = obj.tell() print(data) obj.close()
flush,強制將內存中的數據寫入到硬盤
v = open('a.txt',mode='a',encoding='utf-8') while True: val = input('請輸入:') v.write(val) v.flush() v.close()
v = open('a.txt',mode='a',encoding='utf-8') v.close()
with open('a.txt',mode='a',encoding='utf-8') as v: data = v.read() # 縮進中的代碼執行完畢後,自動關閉文件
with open('a.txt',mode='r',encoding='utf-8') as f1: data = f1.read() new_data = data.replace('飛灑','666') with open('a.txt',mode='w',encoding='utf-8') as f1: data = f1.write(new_data)
f1 = open('a.txt',mode='r',encoding='utf-8') f2 = open('b.txt',mode='w',encoding='utf-8') for line in f1: new_line = line.replace('大大','小小') f2.write(new_line) f1.close() f2.close()
with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2: for line in f1: new_line = line.replace('阿斯', '死啊') f2.write(new_line)
with open('log','r') as f: ...
如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。
在Python 2.7 後,with又支持同時對多個文件的上下文進行管理,即:
with open('log1') as obj1, open('log2') as obj2: pass