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.

+3


source to share


5 answers


In an ugly, code game:

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

      



If you want something more readable:

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

      

+1


source


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

      



From there, you can add the date in the middle.

+1


source


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.

demo

+1


source


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

      

0


source


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'

      

0


source







All Articles