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

Xóa file swap (.swp) đệ quy trong Python

File swap (Vim, etc.) có đuôi .swp. Dùng os.walk + str.endswith() + os.remove().

Ví dụ

import os

mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in files:
        if file.endswith('.swp'):
            full_path = os.path.join(root, file)
            os.remove(full_path)
            print(f"Deleted: {full_path}")

Pythonic hơn: glob + pathlib (Python 3.5+)

from pathlib import Path

for swp_file in Path('my_folder').rglob('*.swp'):
    swp_file.unlink()
    print(f"Deleted: {swp_file}")

Cẩn thận

  • Kiểm tra kỹ trước khi xóa hàng loạt.
  • Backup hoặc dry-run (chỉ in, không xóa) trước.