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

Viewed 373

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.

3 Answers

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)

Try this:

import pandas as pd
import os
  
## Your Dataframe
data = {
        'key':['hi-1', 'hi-2', 'hi-3', 'hi-4'],
        'name':['aa', 'fg', 'dc', 'vb']
      }
df = pd.DataFrame(data)

## File path
path = r'home\folder'

for rownum, row in df.iterrows():
  # Get names
  old_name = row['name']
  new_name = row['key']
  ## Rename file in folder
  os.rename(os.path.join(path, old_name), os.path.join(path, new_name))

Here is a solution you can try out,

for i in df.to_dict(orient='records'):
    if os.path.exists(rf'F:\folder\{i["name"]}.txt'):
        os.rename(
            rf'F:\folder\{i["name"]}.txt', rf'F:\folder\{i["key"]}.txt'
        )
Related