Renaming excel files based on content

I am trying to rename my excel files in a folder based on the content of cell a1, I am using pandas to parse the files and store the value of cell a1, then using that value to rename the file.

The code is as follows:

import os
import pandas as pd
import glob

source_dir = r'C:UsersAhmed_AbdelmuniemDesktopRenameFolder'

file_names = glob.glob(os.path.join(source_dir, '*.xlsx'))

for file_name in file_names:
    df1 = pd.read_excel(file_name)
    new_name = df1.iat[0,0]
    # print (new_name)
    file_name.rename(file_name.with_name(new_name))

I get the following traceback:

C:UsersAhmed_AbdelmuniemAppDataLocalProgramsPythonPython39python.exe C:/Users/Ahmed_Abdelmuniem/PycharmProjects/Renamer/main.py
Traceback (most recent call last):
  File "C:UsersAhmed_AbdelmuniemPycharmProjectsRenamermain.py", line 13, in <module>
    file_name.rename(file_name.with_name(f"new_name"))
AttributeError: 'str' object has no attribute 'rename'

Process finished with exit code 1

I am not sure what it means by AttributeError: ‘str’ object has no attribute ‘rename’, as the value stored in new_name is a str, I tested it out with print. It produces the following result:

XXX.xlsx
YYY.xlsx

Answer

The variable file_name you are trying to rename is just a str, which does not contain the rename method. You can rename a file using os.rename. See code below.

import os
import pandas as pd
import glob

source_dir = ''

file_names = glob.glob(os.path.join(source_dir, '*.xlsx'))

for file_name in file_names:
    df1 = pd.read_excel(file_name)
    new_name = df1.iat[0,0]
    os.rename(os.path.join(source_dir, file_name), os.path.join(source_dir,new_name+".xlsx"))