Rahul Gattu
Rahul Gattu

Reputation: 5

Concatenate Error while adding date format to existing file path in python

Hello stackflowers, I'm newbee here and i need help

I been recently learning pandas library in python and trying to automate the output file, I was successful with it. But when i thought of adding date to the output path the error i'm facing is "can only concatenate list (not "str") to list"

Can anyone help me on this...

#saving in a path

timestamp = datetime.datetime.now()
t = timestamp.year, timestamp.month, timestamp.day

path = r'C:\Users\Revanth\Desktop\pandas_tutorials\New_Idle_Artist_List.xlsx'

split_filename = path.split(".")
exportpath = os.rename(path, split_filename[:-1]+'-'+join(t))

writer = pd.ExcelWriter(exportpath,engine='xlsxwriter',datetime_format='mmm d yyyy')




**Error displayed** : runfile('C:/Users/Revanth/.spyder-py3/Idle_artist_appliction.py', wdir='C:/Users/Revanth/.spyder-py3') Traceback (most recent call last):

  File "C:\Users\Revanth\.spyder-py3\Idle_artist_appliction.py", line 71, in <module>
    exportpath = os.rename(path, [split_filename[:-1]+'-'+join(t)])

TypeError: can only concatenate list (not "str") to list

Upvotes: 0

Views: 400

Answers (1)

FObersteiner
FObersteiner

Reputation: 25564

Here's an example of my comment, how you could construct the exportpath using the Path class from the pathlib module. It might look complicated at first sight but will pay off on the long run since very convenient once you get used to it.

from datetime import datetime
from pathlib import Path

path = Path(r'C:\Users\Revanth\Desktop\pandas_tutorials\New_Idle_Artist_List.xlsx')

datestring = datetime.now().strftime('%Y-%m-%d')
# e.g. '2020-06-28'

exportpath = path.parent/f'{path.stem}-{datestring}{path.suffix}'
# e.g. WindowsPath('C:/Users/Revanth/Desktop/pandas_tutorials/New_Idle_Artist_List-2020-06-28.xlsx')
  • First, we make a Path object from the path string (raw string mode since we have single backslashes)
  • Construct today's year-month-day string using strftime
  • Make the exportpath. path.parent is everything except filename. Then we can use a / to combine that with a new filename which we construct using an f-string. path.stem is the filename without its extension; path.suffix is only the extension.

Refs: pathlib, f-strings

Upvotes: 1

Related Questions