如何用Python检测指定类型文件并将.xlsx文件移至回收站
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
globorpathlibmodules (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

