Search code examples
pythonpandasfiledirectoryshutil

Move file using specific nav path to another folder


I have a list of navigation paths to specific files, which all come from different folders. I'd like to move them all to a new folder.

Specifically, my data is formatted in two columns in a dataframe, where I'd like to move each file to its new folder. (Each row describes a file.)

My input:

df = pd.DataFrame({'old_path': ['/Users/myname/images/cat/file_0.jpg', '/Users/myname/images/dog/file_1.jpg', '/Users/myname/images/squirrel/file_2.jpg'], 
                  'new_path': ['/Users/myname/mydir/file_0.jpg', '/Users/myname/mydir/file_1.jpg', '/Users/myname/mydir/file_2.jpg'], 
                 })

However, I have yet to figure out how to modify the code below to do this in a loop or anything similarly helpful: How to move a file in Python?

import os
import shutil

shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

In this example, all the files are being moved to the same folder. But, it'd be great if the answered code were generalizable to send files to different folders, too.


Solution

  • Use zip with a for loop:

    for old, new in zip(df['old_path'], df['new_path']):
        shutil.move(old, new)