-1

I have a folder of xlsx files that I want to edit (add columns...) and save with a new name. This code here works but saves in a new directory with same name. How can I modify the second last line of the code to give it an extension to the original name (i.e. originalname_addtext.xlsx)

from pathlib import Path
from openpyxl import load_workbook

cwd = Path(os.getcwd())
source = cwd / Path('/Users/lidia/Desktop/xlsx/')
dest = cwd / Path('/Users/lidia/Desktop/output/')
for filename in source.glob('*.xlsx'):

.....


wb.save(dest / filename.name) 
wb.close()
LZed
  • 1
  • 2
  • so, your question is to "How to add a custom text to file name before saving, in Python"?like below? https://stackoverflow.com/questions/37487758/how-to-add-an-id-to-filename-before-extension https://stackoverflow.com/questions/6915698/how-do-i-add-text-to-multiple-filenames-using-python – raja777m Sep 23 '20 at 00:54

1 Answers1

1

Instead of this:

wb.save(dest / filename.name) 

You want this:

wb.save(dest / f'{filename.stem}_addtext{filename.suffix}') 

filename.stem gets you the .name without the suffix (i.e. '.xlsx')

Grismar
  • 27,561
  • 4
  • 31
  • 54