【问题标题】:Python regex: rename all files except those with today's date in the namePython regex:重命名所有文件,但名称中包含今天日期的文件除外
【发布时间】:2018-11-06 21:54:50
【问题描述】:

我正在尝试重命名文件夹中的所有文件并从文件名中删除空格。所有文件的名称中都有 YY-mm-dd 格式的今天日期。以下是我迄今为止设法创建的内容。

但是,运行给我一个“TypeError:startswith first arg must be str or a tuple of str, not _sre.SRE_Pattern”

import os
import datetime
import re
today = datetime.datetime.now()
path = "/some/path/"
regex = re.compile(".*" + today.strftime("(%Y-%m-%d)") + ".*(.log$)", re.IGNORECASE)
for file in os.listdir(path):
    os.rename(file.startswith(regex), file.replace(" ","_")

注意:我知道在当前状态下,它会查找今天的日期,而不是除今天之外的所有日期。我已将其保持原样进行测试,一旦它起作用就会反转匹配正则表达式。

提前谢谢你。

【问题讨论】:

    标签: python regex file rename


    【解决方案1】:

    看起来答案在错误中是正确的,startswith 的参数必须是字符串,而不是编译的正则表达式模式。所以基本上它告诉你startswith 不能将正则表达式模式作为参数。但是,嘿-这就是正则表达式的用途!

    您应该使用正则表达式模式^ 来表示行的开头,然后将文件名与该模式匹配。

    这是一个粗略的例子:

    ...
    regex = re.compile("^.*" + today.strftime("(%Y-%m-%d)") + ".*(.log$)", re.IGNORECASE)
    for file in os.listdir(path):
         if regex.match(file): 
             # do something 
    

    【讨论】:

    • 这样做不会再引发错误,但是如果我将 print(file) 放在 if 语句下方,我不会得到任何结果。
    【解决方案2】:

    您的 file.startswith(regex) 将返回 True 或 False。我认为您想要的是重命名与您的正则表达式匹配的文件。你需要在你的 for 循环下使用另一个“if”语句来检查文件名是否以正则表达式开头,然后你需要运行 os.rename:

    for file in os.listdir(path):
        if file.starstwith(regex):
            os.rename(file, file.replace(" ", "_"))
    

    【讨论】:

    • 我认为if file.starstwith(regex): 会抛出相同的TypeError,因为regex 是一个已编译的正则表达式模式(但必须是字符串或元组)。
    猜你喜欢
    • 2022-12-24
    • 1970-01-01
    • 2015-11-19
    • 2011-03-01
    • 2016-10-06
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    相关资源
    最近更新 更多