天天看點

Python 知識點總結篇(3)

檔案操作

  • 對檔案操作流程
    • 打開檔案,得到檔案句柄并指派給一個變量;
      • 通過句柄對檔案進行操作;
        • 關閉檔案;
  • with

    :自動關閉檔案;
with open('log', 'r') as f:
	...           

複制

  • 檔案操作之

    open()

Python 知識點總結篇(3)

模式比對與正規表達式

  • 正規表達式:簡稱regex,是文本模式的描述方法;
  • 正規表達式比對步驟:
    • 導入正規表達式子產品

      re

    • re.compile()

      函數建立一個

      Regex

      對象(記得使用原始字元串);
    • Regex

      對象的

      search()

      方法傳入想要查找的字元串,傳回一個

      Match

      對象;
    • 調用

      Match

      對象的

      group()

      方法,傳回實際比對文本的字元串;
  • 管道:

    |

    ,用于比對多個表達式中的一個,比對多個分組;
  • 問号:

    ?

    ,實作可選比對;
>>> import re
>>> batRegex = re.compile(r'Bat(wo)?man')
>>> mo1 = batRegex.search('The Adventures of Batman.')
>>> print(mo1.group())
Batman
>>> mo2 = batRegex.search('The Adventures of Batwoman.')
>>> print(mo2.group())
Batwoman           

複制

  • 星号:

    *

    ,比對零次或多次,即星号之前的分組,可以在文本中出現任意次;
>>> import re
>>> batRegex = re.compile(r'Bat(wo)*man')
>>> mo1 = batRegex.search('The Adventures of Batwowoman')
>>> print(mo1.group())
Batwowoman           

複制

  • 加号:

    +

    ,比對一次或多次,加号前面的分組必須"至少出現一次”;
>>> import re
>>> batRegex = re.compile(r'Bat(wo)+man')
>>> mo1 = batRegex.search('The Adventures of Batwowoman')
>>> print(mo1.group())
Batwowoman
>>> mo2 = batRegex.search('The Adventures of Batman')
>>> print(mo2 == None)
True           

複制

  • 花括号:

    { }

    ,比對特定次數;
>>> import re
>>> batRegex = re.compile(r'ha{3}')
>>> mo1 = batRegex.search('hahaha')
>>> print(mo1.group())
hahaha
>>> mo2 = batRegex.search('haha')
>>> print(mo2 == None)
True           

複制

  • findall()

    方法傳回結果:
    • 若調用在一個沒有分組的正規表達式上,則傳回一個比對字元串的清單,如

      ['123-324-5832', '324-589-0983']

    • 若調用在一個有分組的正規表達式上,則傳回一個字元串的元組的清單(每個分組對應一個字元串),如

      [('123', '453', '4324'), ('343', '654', '3245)]

  • ^xxx

    :表示字元串必須以

    xxx

    開始;
  • xxx$

    :表示字元串必須以

    xxx

    結尾;
  • 絕對路徑:從根檔案夾開始;
  • 相對路徑:相對于程式的目前工作目錄;
  • 讀寫檔案的步驟:
    • 調用

      open()

      函數,傳回一個

      File

      對象;
    • 調用

      File

      對象的

      read()

      write()

      方法;
    • 調用

      File

      對象的

      close()

      方法,關閉該檔案;
  • 永久删除檔案和檔案夾:
    • os.unlink(path)

      删除

      path

      處的檔案;
    • os.rmdir(path)

      将删除

      path

      處的檔案夾,但檔案夾必須為空;
    • shutil.rmtree(path)

      删除

      path

      處的檔案夾,包含的所有檔案和檔案夾都會被删除;

調試

  • 反向跟蹤:Python遇到錯誤,就會産生錯誤資訊,這些資訊包含了出錯資訊、導緻該錯誤的代碼行号,以及導緻該錯誤的函數調用的序列(調用棧);