Python旅途——文件操做

Python——文件操做

1.理解文件操做

  • 可能有的時候有人會在想爲何要對文件進行操做,不管對於文件仍是網絡之間的交互,咱們都是創建在數據之上的,若是咱們沒有數據,那麼不少的事情也就不可以成立,好比咱們淘寶買了一件衣服,那麼淘寶是如何知道咱們的相關信息的呢?爲何不會把咱們的衣服發給別人呢?這些都基於咱們自己的數據。而咱們的數據通常都存放在哪呢?python

  • 在咱們沒有接觸數據庫以前,咱們得到數據的手段也只能是從文件中獲取,所以Python中的文件操做也是十分的重要。linux

2.文件的基本操做

操做文件時,通常須要經歷以下步驟數據庫

  • 打開文件
  • 操做文件
  • 修改文件
  • 關閉文件

1.打開文件:

  • 文件句柄 = file('文件路徑', '模式'),打開文件時,須要指定文件路徑和以何等方式打開文件,打開後,便可獲取該文件句柄,往後經過此文件句柄對該文件操做。
  • 打開文件的模式有:
    • r,只讀模式(默認)。
    • w,只寫模式。【不可讀;不存在則建立;存在則刪除內容;】
    • a,追加模式。【可讀;不存在則建立;存在則只追加內容;】
  • "+"表示能夠同時讀寫某個文件
    • r+,可讀寫文件。【可讀;可寫;可追加】
    • w+,寫讀
    • a+,同a
  • "b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標註)
    • rb
    • wb
    • ab

2.操做文件

  • 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()

3. 關閉文件

  • 方式一
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()
    # 縮進中的代碼執行完畢後,自動關閉文件

4. 文件內容的修改

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)

5.with

  • 爲了不打開文件後忘記關閉,能夠經過管理上下文,即:
with open('log','r') as f: 

    ...
  • 如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。

  • 在Python 2.7 後,with又支持同時對多個文件的上下文進行管理,即:

with open('log1') as obj1, open('log2') as obj2:
    pass
相關文章
相關標籤/搜索