Search code examples
pythondataframedirectoryrenameglob

How to change the file names in a folder based on a column elements in a data frame using python


I have a data frame 'df' and a folder(path: F:\folder) that contains files with names the same as df['name']. i.e. aa, fg, dc, and vb.

df=
key    name
hi-1   aa
hi-2   fg
hi-3   dc
hi-4   vb

I am interested in changing the names of these files in the folder with their corresponding elements in the same row of the df['key'] column. i.e. rename file aa to hi-1, fg to hi-2, and so on.

I tried to do this by:

import glob, os
os.chdir(r'F:\folder')

for file in glob.glob("*.txt"):
    os.rename(file, df['key'])

However, it is not working, and also it will assign the file names based on the order in which the strings are saved in the column df['key'], which will be incorrect because files can be in a different order in the folder.


Solution

  • This is one way to do it:

    import os
    
    os.chdir("path_to_your_folder")
    names_dict = dict(zip(df['key'], df['name']))
    
    for new_name, old_name in names_dict.items():
        os.rename(old_name, new_name)