Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Trích xuất phần mở rộng file trong Python (os.path.splitext)

os.path.splitext(path) tách path thành tuple (root, ext) với ext bao gồm dấu chấm.

Ví dụ

import os
file_name = 'my_file.txt'
root, ext = os.path.splitext(file_name)
print(root)  # 'my_file'
print(ext)   # '.txt'

Kết quả

('my_file', '.txt')

Lưu ý

  • Chỉ tách phần mở rộng cuối cùng: archive.tar.gz → ('archive.tar', '.gz').
  • Không có extension → ext = ''.
  • File ẩn Unix .bashrc → ('.bashrc', '') (coi như không có extension).

pathlib (Python 3.4+)

from pathlib import Path
p = Path('my_file.txt')
print(p.suffix)   # '.txt'
print(p.stem)     # 'my_file'
print(p.suffixes) # ['.txt'] (list all suffixes: .tar.gz → ['.tar', '.gz'])