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

咨询:如何用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 of 17)
  • The matching function 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 (since os.listdir returns a list of strings, not objects with an index method 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.remove line and keep the print statement 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:37:47