如何轻松拆分文件名并附加日期/时间?

时间:2017-08-01 16:50:21

标签: python regex split

让我说我有:

attachment.FileName = "hello.pdf"

我希望它能产生:

hello_July5.pdf

我知道如何获取我追加的日期,但我如何轻松地在“。”之间进行分割。然后在它之间添加变量date

我知道这很简单,我只是在寻找最快的解决办法。

5 个答案:

答案 0 :(得分:1)

以丑陋的,代码高尔夫的方式:

("_" + myDate + ".").join(filename.split("."))

如果你想要更具可读性的东西:

filePieces = filename.split(".")
newFilename = "{0}_{1}.{2}".format(filePieces[0],myDate,filePieces[1])

答案 1 :(得分:1)

name = 'test.pdf'
print(os.path.splitext(name))
# ('test', '.pdf')

从那里你可以将日期添加到中间。

答案 2 :(得分:1)

您可以使用正则表达式执行此操作,但os.path将更可靠。

import os.path
from datetime import date

def add_date(fname, day=date.today()):
    return day.strftime('_%b%d').join(os.path.splitext(fname))

在格式字符串中,%b表示月份的三个字母缩写,%d表示当月日期的数字表示。

demo

答案 3 :(得分:0)

regex101

(^.*)(\.[^.]+$)

描述

 1st Capturing Group (^.*)
   ^ asserts position at start of a line
   .* matches any character (except for line terminators)
     * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
 2nd Capturing Group (\.[^.]+$)
   \. matches the character . literally (case sensitive)
     Match a single character not present in the list below [^.]+
   + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
   . matches the character . literally (case sensitive)
   $ asserts position at the end of a line

答案 4 :(得分:0)

pathlib 是一种处理路径名,文件名和目录的好方法。

箭头非常适合处理各种日期和时间计算。

预赛:

>>> class Attachment:
...     pass
... 
>>> attachment = Attachment()
>>> attachment.FileName = 'hello.pdf'
>>> import pathlib
>>> import arrow

创建所需日期。将其拆分为p中的组件部分。将所需的部分组合在一起,包括适当格式化的日期到新文件名中。

>>> a_date = arrow.get('2017-07-05', 'YYYY-MM-DD')
>>> p = pathlib.PurePath(attachment.FileName)
>>> attachment.FileName = p.stem + a_date.format('_MMMMD') + p.suffix
>>> attachment.FileName 
'hello_July5.pdf'