第三章 文件操做

3.11 文件操做

1.  文件基本操做

  obj = open('路徑',mode='模式',encoding='編碼')
  obj.write() # 寫入
  obj.read()   # 讀取
  obj.close() #關閉

2.  打開模式

    • r / w / a 【只讀只寫字符串】 *ide

    • r+ / w+ / a+ 【可讀可寫字符串】ui

    • rb / wb / ab 【只讀只寫二進制】 *編碼

    • r+b / w+b / a+b 【可讀可寫二進制】spa

3.  操做

    • read() , 所有讀到內存code

    • read(1) blog

      • 1表示一個字符內存

        obj = open('a.txt',mode='r',encoding='utf-8')
        data = obj.read(1) # 1個字符
        obj.close()
        print(data)
      • 1表示一個字節utf-8

        obj = open('a.txt',mode='rb')
        data = obj.read(3) # 1個字節
        obj.close()
    • write(字符串)字符串

      obj = open('a.txt',mode='w',encoding='utf-8')
      obj.write('中午你')
      obj.close()
    • write(二進制)input

      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)

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

4.  關閉文件

  文藝青年

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

 

5. 文件內容的修改

  1. 示例

    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)
    View Code

     

  2. 大文件修改

    # 方式一
    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)
    View Code
相關文章
相關標籤/搜索