咨询:如何用Python正则表达式删除目录中含17的指定格式文件
Solution to Delete Files Matching
??_????17*.* Pattern in Python Hey there! Let's get this file deletion task sorted out properly. First, let's recap your requirement: you need to delete all files in a target folder where the filename follows the pattern ??_????17*.* (must contain _ and 17, while skipping files with 18), with any file extension allowed.
Issues with Your Current Code
Before diving into the fix, let's quickly go over what's not working in your existing code:
- The regex you wrote has incorrect escaping (like
\\[_]instead of just_, and\\[1]\\[7]instead of17) - The
matchingfunction returns "Files don't exist!" when a match is found, which is the opposite of what you need - You're trying to use
testfolder.index(matching)which doesn't make sense (sinceos.listdirreturns a list of strings, not objects with anindexmethod that takes a function) - The loop logic is broken—you can't call
item.name()on a string filename
Simplest Solution: Use the glob Module
You mentioned the glob module, and it's perfect here because it's designed exactly for matching file patterns. Here's a clean, working implementation:
import os import glob # Replace with your actual folder path dir_name = "/Python/Test_folder" # The glob pattern: ?? = 2 any chars, _ = literal underscore, ???? = 4 any chars, 17 = literal 17, * = any remaining chars pattern = os.path.join(dir_name, "??_????17*") # Iterate over all matching files for file_path in glob.glob(pattern): # Make sure we're deleting a file, not a subfolder if os.path.isfile(file_path): print(f"Deleting: {file_path}") # Optional: verify before deleting os.remove(file_path)
Alternative: Use Regular Expressions (For More Control)
If you prefer using regex for more precise matching, here's a corrected version using re:
import os import re dir_name = "/Python/Test_folder" # Regex pattern: ^ start of string, .{2} any 2 chars, _ literal, .{4} any 4 chars, 17 literal, .* any remaining chars file_pattern = re.compile(r'^.{2}_.{4}17.*') for filename in os.listdir(dir_name): file_path = os.path.join(dir_name, filename) # Skip directories, only process files if os.path.isfile(file_path): # Check if the filename matches our pattern if file_pattern.match(filename): print(f"Deleting: {file_path}") # Optional: verify first os.remove(file_path)
Important Notes
- Test First: Comment out the
os.removeline and keep theprintstatement to make sure you're targeting the right files before deleting anything - Backup: Always make a backup of your folder before running deletion scripts—better safe than sorry!
- Path Handling: Use absolute paths if you're unsure about the working directory, or use
os.path.abspath()to convert relative paths - Permissions: Ensure your script has write permissions for the target folder
内容的提问来源于stack exchange,提问作者Alexander Larionov
相关产品推荐
相关产品推荐

