How easy is it to split the filename and add the date / time?
Let's say I have:
attachment.FileName = "hello.pdf"
I would like this to result in:
hello_July5.pdf
I know how to get the date that I am adding, but how easy it is for me to split between "." and then add a variable in date
between?
I know this is easy, I'm just looking for a quick solution.
source to share
You can do this with a regular expression, but it os.path
will be more reliable.
import os.path
from datetime import date
def add_date(fname, day=date.today()):
return day.strftime('_%b%d').join(os.path.splitext(fname))
In the format string, %b
represents the three-letter abbreviation of the month, and %d
is the numeric representation of the day of the month.
source to share
regex101
(^.*)(\.[^.]+$)
Description
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
source to share
pathlib is a good way to handle path names, file names and directory names.
the arrow is good for handling various date and time calculations.
Qualifying:
>>> class Attachment:
... pass
...
>>> attachment = Attachment()
>>> attachment.FileName = 'hello.pdf'
>>> import pathlib
>>> import arrow
Create the required date. Divide it into components in p
. Collect the required chunks, including the appropriate formatted date, into a new filename.
>>> 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'
source to share