简体   繁体   中英

Python, rename files in directory

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 (ie 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()

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 (ie '.xlsx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM