【问题标题】:Delete certain files from a directory using regex regarding a specific detail in file names使用关于文件名中特定细节的正则表达式从目录中删除某些文件
【发布时间】:2018-06-30 06:59:23
【问题描述】:

在这里,我正在尝试创建一个代码,该代码将根据掩码删除文件夹中的文件。应删除所有包含 17 的文件,文件夹中文件的一般格式为 ??_????17*.* 哪里? - 任何符号 1..n,A..z; * - 任意长度的符号; _ 和 17 - 在任何文件中(其他文件也包含 18),其扩展名无关紧要。文件夹中文件的某些示例:AB_DEFG17Something.Anything - Copy (2).txt; AB_DEFG18Something.Some - 复制 (3).txt... p.s.为之前的不充分和不准确的解释道歉。如果文件名称相似,您对 globe.globe 的看法是正确的。 很高兴收到有关此任务的观点,我希望它对其他人有用。

import os
import re

dir_name = "/Python/Test_folder"    # open the folder and read files
testfolder = os.listdir(dir_name)

def matching(r, s):                 # condition if there's nothing to match
    match = re.search(r, s)
    if match:
        return "Files don't exist!"

matching(r'^\w\w\[_]\w\w\w\w\[1]\[7]\w+\[.]\w+', testfolder)  # matching the mask of files

for item in testfolder.index(matching):
    if item.name(matching, s):
        os.remove(os.path.join(dir_name, item))

# format of filenames not converted :  ??_????17*.* 

【问题讨论】:

标签: python regex match


【解决方案1】:

文件夹中带有??_????17*.* 模式的所有文件都将使用此代码删除:

import os
import re

dir_name = "/Python/Test_folder"    # open the folder and read files
testfolder = os.listdir(dir_name)

p = re.compile(r'^[1-9\w]{2}_[1-9\w]{4}[1][7][\w]+\.[\w]+')
for each in testfolder:
    k = p.match(each)
    if k == None:
        continue
    os.remove(os.path.join(dir_name, each))

希望这是你需要的。

【讨论】:

  • \d 已经包含在\w 中,所以[\d\w]\w完全相同
  • @Toto 以及 \w 也会检查 0-9。所以你可以用\w 替换\d\w。无论如何,两者都完美无缺。感谢您指出这一点。
  • 感谢 Toto 和 Theausome,你们迫使我更多地学习和理解正则表达式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多