You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python检测指定类型文件并将.xlsx文件移至回收站

Handling .xlsx Files in Python: Detect, Classify, and Move to Recycle Bin

General Rule for Targeting .xlsx Files

When grouping files by type, the standard approach is to match against their file extensions—the segment after the last dot in a filename. For .xlsx files, this means checking if a filename ends with .xlsx. A quick tip: some systems are case-sensitive, so you might want to account for uppercase variants like .XLSX by normalizing the filename to lowercase first.

Two reliable ways to do this:

  • Use string methods like str.endswith() (great for basic, straightforward checks)
  • Use the glob or pathlib modules (more powerful for pattern matching across nested directories)

Code to Move .xlsx Files to the Recycle Bin

Heads up: shutil.move() moves files to a specified directory, but it doesn’t natively send items to your system’s recycle bin—it acts like a regular file move/delete. To safely send files to the recycle bin across Windows, macOS, and Linux, use the send2trash library—it’s built exactly for this cross-platform use case.

Step 1: Install the library

First, install send2trash via pip:

pip install send2trash

Step 2: Full Code Implementation

This script scans your target folder, identifies all .xlsx files, and sends them to the recycle bin:

import os
from send2trash import send2trash

target_folder = "/user/documents/folder"

# Loop through every item in the target folder
for filename in os.listdir(target_folder):
    file_path = os.path.join(target_folder, filename)
    
    # Skip directories, only process files
    if os.path.isfile(file_path):
        # Check for .xlsx (case-insensitive)
        if filename.lower().endswith(".xlsx"):
            try:
                send2trash(file_path)
                print(f"Successfully sent {filename} to the recycle bin")
            except Exception as e:
                print(f"Failed to send {filename}: {str(e)}")

If you prefer the modern, object-oriented pathlib module (cleaner for path handling), here’s an alternative version:

from pathlib import Path
from send2trash import send2trash

target_folder = Path("/user/documents/folder")

# Find all .xlsx files (use "*.xlsx" for top-level only, "**/*.xlsx" to include subfolders)
for xlsx_file in target_folder.glob("*.xlsx"):
    if xlsx_file.is_file():
        try:
            send2trash(xlsx_file)
            print(f"Successfully sent {xlsx_file.name} to the recycle bin")
        except Exception as e:
            print(f"Failed to send {xlsx_file.name}: {str(e)}")

How to Detect Specific File Types in a Folder

Detecting specific file types uses the same pattern-matching logic as above. Here are three common methods:

Method 1: Using os module + endswith()

import os

target_folder = "/user/documents/folder"
xlsx_files = []

for filename in os.listdir(target_folder):
    file_path = os.path.join(target_folder, filename)
    if os.path.isfile(file_path) and filename.lower().endswith(".xlsx"):
        xlsx_files.append(file_path)

print(f"Found {len(xlsx_files)} .xlsx files:")
for file in xlsx_files:
    print(file)

Method 2: Using glob (simpler pattern matching)

import glob

# Get top-level .xlsx files; add recursive=True to include subfolders
xlsx_files = glob.glob("/user/documents/folder/*.xlsx")

print(f"Found {len(xlsx_files)} .xlsx files:")
for file in xlsx_files:
    print(file)

Method 3: Using pathlib (modern, readable approach)

from pathlib import Path

target_folder = Path("/user/documents/folder")
# Use rglob instead of glob to include subfolders
xlsx_files = list(target_folder.glob("*.xlsx"))

print(f"Found {len(xlsx_files)} .xlsx files:")
for file in xlsx_files:
    print(file.resolve())  # Prints the full absolute path

Pick the method that fits your coding style—all work reliably!

内容的提问来源于stack exchange,提问作者L Cessford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:34:18