0

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)
  • 1
    Does this answer your question? [How to rename a file using Python](https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python) – Dan Dec 13 '22 at 04:27
  • @Dan thank you for the link. Maybe it's me but I could not find the appropriate script. Can you tell me what it is please? thanks – QuickSilver42 Dec 13 '22 at 04:32
  • That is how to rename files in Python. Any file. As to which files you want to rename under what circumstances and where, you didn't say any of that in your question. So now you can code that and have the code to do the actual rename. If unsure how to do those things, ask a more specific question and show what you have tried, where you're stuck, and specify what you are trying to do. – Dan Dec 13 '22 at 04:34

2 Answers2

0

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'))
Akshat Tamrakar
  • 2,193
  • 2
  • 13
  • 21
0

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")