How to change file name in a folder based on a DataFrame column

Question:

I have a folder consists several files in the directory E:folder and looks like the following.

-folder
   -old1.jpg
   -old2.jpg
   -old3.jpg
   -...

and I would like to change the name of these files based on the dataframe df column "new_name".

new_name
abc1
def2
ghi3
...

I want to match the files with the dataframe based on the date modified. In other words, the file created first should be replaced with the first row of the dataframe df['new_name'].

So name of the file "old1.jpg" should be renamed with "abc1.jpg".

I’ve tried something like this but still couldn’t figure out how to match the files with the dataframe.

import os

file_name = os.path.basename(file_path)
names_dict = dict(zip(file_name, df['new_name']))

for new_name, old_name in names_dict.items():
    os.rename(old_name, new_name)

Any help would appreciate it!

Asked By: complog

||

Answers:

Here’s a possible answer. Using pathlib is usually recommended for file manipulation instead of using os directly

from pathlib import Path

folder = 'E:folder'
#getting all objects in folder and keeping only files
files = list(path for path in Path(folder).iterdir() if path.is_file()) 
#sorting files based on ST_MTIME which represents the time of last modification
files.sort(key = lambda file: file.stat().st_mtime)

for new_name, file in zip(df['new_name'], files):
#extension is given by file.suffix
   file.rename(Path(folder, new_name + file.suffix))

This minimal solution assumes that df['new_name'] is already sorted by ascending time of modification. You should probably add checks that df['name'] and files should be the same length. As it is now if the sizes don’t match the loop will end upon reaching the end of the smallest of the two iterables.

There is also a last issue depending on your OS and/or Python version. Modified dates should work correctly on any UNIX-like OS but I think that Windows has not always been consistent with the ST_MTIME variable. So that’s one thing to check on your end

Answered By: rorshan