3

Let's say I have:

attachment.FileName = "hello.pdf"

I would like for it to result in:

hello_July5.pdf

I know how to get the date what I am appending, but how do I easily make a split between the "." and then add the variable date between it?

I know this is simple, I am just looking for the quickest fix possible.

sgerbhctim
  • 3,420
  • 7
  • 38
  • 60
  • Split using dot, then do `arr[0] + '_' + month + '.' + arr[1]` – anubhava Aug 01 '17 at 16:55
  • Possible duplicate of [changing file extension in Python](https://stackoverflow.com/questions/2900035/changing-file-extension-in-python) in spirit not exact context. – abc123 Aug 01 '17 at 17:12

5 Answers5

1

In an ugly, code-golf way:

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

If you want something more readable:

filePieces = filename.split(".")
newFilename = "{0}_{1}.{2}".format(filePieces[0],myDate,filePieces[1])
stackPusher
  • 6,076
  • 3
  • 35
  • 36
1
name = 'test.pdf'
print(os.path.splitext(name))
# ('test', '.pdf')

From there you can append the date in the middle.

Quinn Weber
  • 927
  • 5
  • 10
1

You could do it with a regex, but 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 the numerical representation of the day of the month.

demo

wbadart
  • 2,583
  • 1
  • 13
  • 27
0

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
abc123
  • 17,855
  • 7
  • 52
  • 82
0

pathlib is a nice way of handling pathnames, filenames and directories.

arrow is nice for handling various date and time calculations.

Preliminaries:

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

Create the required date. Split it into its component pieces in p. Assemble the required pieces, including a suitably formatted date into the 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'
Bill Bell
  • 21,021
  • 5
  • 43
  • 58