【问题标题】:Python filename regular expression extractPython文件名正则表达式提取
【发布时间】:2018-07-24 07:24:34
【问题描述】:

我正在尝试将文件从一个文件夹复制粘贴到另一个文件夹。但是这个文件每天都会产生,所以文件名会改变。我想创建一个 reg 表达式来识别文件夹中的正确文件。我不熟悉正则表达式,所以也许我可以得到一些提示?

复制文件的文件路径如下: G:\贸易报告_Daily1_FI_2000_2018-07-24-06-40-42.xlsx

这部分在所有文件中都是相同的。

交易报告_每日 这部分发生了变化。

2018-07-24-06-40-42.xlsx

我想我可能会使用 datetime 模块来帮助确定正确的日期。但是日期 (-06-40-42) 之后的数字是随机的。

import re, os

from datetime import date
today = date.today()

RNRegex = re.compile(r'Rolfe and Nolan Trade Reports_Daily1_FI_2000_' + str(today) +'-\d\d-\d\d-\d\d.xlsx')
#os.listdir(r'G:RLN FI Reports')

for RNfile in os.listdir(r'G:\RLN FI Reports'):
    mo = RNRegex.search(RNfile)

    if mo == None:
        continue
    else:
        print(mo)

EDIT:
My Output now

runfile('C:/Users/z000xxx/.spyder-py3/untitled21.py', 
wdir='C:/Users/z000xxc/.spyder-py3')
<_sre.SRE_Match object; span=(0, 69), match='Rolfe and Nolan Trade 
Reports_Daily1_FI_2000_2018>

【问题讨论】:

  • 不要在 Python 中对变量使用大写命名!不要在 Windows 路径中使用空格!
  • 这对我有用RNRegex = re.compile(r'Rolfe and Nolan Trade Reports_Daily1_FI_2000_' + str(today) +'-\d{2}-\d{2}-\d{2}.xlsx')
  • 请不要破坏您的帖子。如果您认为您的问题没有用或不再有用,则应将其删除,而不是编辑掉实际上使其成为问题的所有数据。通过在 Stack Exchange 网络上发布,您已授予 SE 分发该内容的不可撤销的权利(根据 CC BY-SA 3.0 许可)。根据 SE 政策,任何破坏行为都将被撤销。

标签: python regex python-3.x


【解决方案1】:

这应该可以解决问题:

 today = date.strftime(date.today(), "%Y-%m-%d")

 RNRegex = re.compile("Rolfe and Nolan Trade Reports_Daily1_FI_2000_" + today + "(-\d{2}){3}\.xlsx")

附带说明,如果您想获取无法打印search 的结果的文件名,则需要使用print(mo.group(0))

我不得不使用date.strftime 来格式化date.today,因为它有时不会将月份和日期打印为个位数

编辑:只匹配今天的文件

【讨论】:

  • 不要转义_,它们是单词字符(与\w 匹配),因此对于正则表达式引擎来说并不特殊。
  • 哦,我可能没明白你在问什么,你想只得到今天日期的文件吗?
【解决方案2】:

您也可以使用glob.glob('G:\Path\To\Files\Keywords_*.ext')。这与 Windows 命令 dir 的行为类似,星号为贪婪字符。

示例:全局

>> import glob
>> glob.glob('C:\Windows\*.dll')
['C:\\Windows\\EvtMessage.dll',
 'C:\\Windows\\RtlExUpd.dll',
 'C:\\Windows\\twain.dll',
 'C:\\Windows\\twain_32.dll']

示例:窗口命令

C:\>dir /B C:\Windows\*.dll
EvtMessage.dll
RtlExUpd.dll
twain.dll
twain_32.dll

在这个例子中,我没有在文件名中使用关键字。您可能想使用Rolfe and Nolan Trade Reports_Daily1_FI_2000_

【讨论】:

  • @LoveisHell import time; import os; os.mkdir('SAP{}'.format(time.strftime('%Y-%m-%d', time.gmtime()))
【解决方案3】:

您可以简单地列出文件夹中的内容并移动以“Rolfe and Nolan Trade Reports_Daily”开头的文件,而无需使用任何正则表达式。看起来像这样:

import os
files = os.listdir('G:\RLN FI Reports')
for f in files:
    if f.startswith('Rolfe and Nolan Trade Reports_Daily'):
        # move the file wherever you want

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2018-09-24
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多