I could not find similar question here but how can i rename using python any .xlsx file in a directory? The goal is not to hardcode the filename to rename it into something else. Any input or advice is much appreciated. Thank you very much.
What I have tried so far. What it does is, it creates another excel file but i just need the .xlsx in C:\Test to be rename as Master.xlsx.
for root, dirs, files in os.walk("C:\Test", topdown=False,):
for name in files:
base_name, ext = os.path.splitext(name) #Split name, extension
if ext in ".xlsx":
df = pd.read_excel(os.path.join(root, name))
df.to_excel(os.path.join(root, 'Master.xlsx'), index=False)
CodePudding user response:
Use OS client for python
import os
os.chdir("C:\Test") #if you are running your code in 'c:\' location you need to do this so that your code will run inside test folder.
for file in os.listdir():
if file.endswith(".xlsx"):
os.rename(file, "new_name.xlsx")
CodePudding user response:
You can find all .xlsx files using the glob module and then rename them using the os module.
To get all the files in a specific folder/directory.
files = glob.glob(directory '/*.xlsx')
then just loop over it to get the list of files and just rename those files using rename().
os.rename(file, new_name)
full code:
import glob
import os
files = glob.glob('./' '/*.xlsx')
for file in files:
os.rename(file, file.replace('.xlsx', '_new.xlsx'))