0

I'm new to python. I want to refresh an excel document and save the file with a datetime suffix like filename_20220706_1554.

I wrote this following script:

import win32com.client
import time
from datetime import datetime
    
print("Refresh_excel function has started")

xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(r"C:\folder\filename_.xlsx")
wb.RefreshAll()

time.sleep(5)

datestring = datetime.strftime(datetime.now(), '%Y%m%d-%H%M')
print(datestring)

wb.Save(r'C:\folder\filename_{datestring}.xlsx')
xlapp.Quit()

But it raises this error:

File "C:\Users\untitled0.py", line 12, in <module>
    wb.Save(r'C:\folder\filename_{datestring}.xlsx')

TypeError: Save() takes 1 positional argument but 2 were given

Any ideas?

Daniel Trugman
  • 8,186
  • 20
  • 41
maverick
  • 3
  • 2

2 Answers2

1

You should use wb.SaveAs(...) instead of wb.Save()

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

This error means you are passing an incorrect number of arguments.

It looks like you intended to use f'string with {arguments}' but instead used r'string with {arguments}' which breaks the string replacement logic.

r'' strings are raw strings, whereas f'' strings are formatted strings.

However, you cannot use \N in formatted strings. You need raw strings for that.

You should probably build the filename in two steps:

filename = f'Hourly_NPI_Sales_Report_{datestring}.xlsx'
filepath = os.path.join(r'C:\NPI\', filename)
Daniel Trugman
  • 8,186
  • 20
  • 41