pathlib and difflib

vivi~發表於2024-06-07

pathlib.Path("a.crt").write_text(a[0])

p.chmod(0o444)
Path.cwd()
p.write_bytes(b'Binary file contents')
p.read_bytes()

Path('setup.py').exists()


class pathlib.WindowsPath(*pathsegments)
WindowsPath('c:/Program Files/')
1. pathlib - 高階用法
pathlib 提供了一個物件導向的檔案系統路徑操作介面。我們來看看如何使用這個庫進行一些更高階的操作:

鏈式方法呼叫
pathlib 允許使用鏈式方法呼叫來簡化檔案操作。例如,你可以直接從一個路徑物件建立、讀取和寫入檔案,而無需中間變數。

python
Copy code
from pathlib import Path

# 建立並寫入檔案
(Path("example_folder") / "test.txt").write_text("Hello, world!")

# 讀取檔案
content = (Path("example_folder") / "test.txt").read_text()
print(content)

# 列出目錄下所有檔案
files = [x for x in Path("example_folder").iterdir() if x.is_file()]
print(files)

# 使用glob模式查詢檔案
py_files = list(Path("example_folder").glob("*.py"))
print(py_files)
路徑操作和檢查
使用 pathlib 進行檔案路徑的操作和狀態檢查非常直觀:

python
Copy code
from pathlib import Path

p = Path("/usr/bin/python3")

# 檢查是否為檔案
if p.is_file():
    print(f"{p} is a file.")

# 檢查是否為目錄
if p.parent.is_dir():
    print(f"{p.parent} is a directory.")

# 解析路徑的各個部分
print(f"Name: {p.name}")
print(f"Suffix: {p.suffix}")
print(f"Parent Directory: {p.parent}")
2. difflib - 高階用法
difflib 是處理文字差異和生成差異報告的強大工具。它可以用來高效地比較檔案內容或生成人類可讀的差異報告。

生成詳細的文字差異
使用 difflib 的 unified_diff 生成具有上下文的差異,這對程式碼稽核尤其有用。

python
Copy code
import difflib
import sys

text1 = "one\ntwo\nthree\nfour\nfive\n".splitlines(keepends=True)
text2 = "zero\none\ntree\nfour\nfive\n".splitlines(keepends=True)

# 生成帶上下文的差異
diff = difflib.unified_diff(text1, text2, fromfile='old.txt', tofile='new.txt')
sys.stdout.writelines(diff)
生成 HTML 差異報告
HtmlDiff 類可以生成一個 HTML 表格,顯示兩個序列之間的差異,適合在Web頁面上展示比較結果。

python
Copy code
import difflib

text1 = "This is a test text file.".split()
text2 = "This is a test shifted text file.".split()

html_diff = difflib.HtmlDiff()
html_content = html_diff.make_file(text1, text2, context=True, numlines=2)

# 輸出 HTML 內容到檔案
with open("diff.html", "w") as f:
    f.write(html_content)