Enterrador99
Enterrador99

Reputation: 131

move files python according value columns

I would like to move some files in python according to some values on python dataframe.

My script already creates the folders and subfolders necessary but I want to move the files(each row in my df is a file/document) to those folders/subfolders.

I have 4 columns(doc_id, path of the file, colA, colB and colC) my df

As you can see I have the path for every document. I was able to create the folders but I want my script to automatically move(for example):

So in folder value1 we will have 3 subfolders --> value8, value11 and value14

Thank you

Upvotes: 4

Views: 1389

Answers (2)

Frenchy
Frenchy

Reputation: 17037

i suppose you haven't delimiters \ or / at the end of your values so if not you adapt the solution:

import pandas as pd
import shutil

def move(src, dest):
    shutil.move(src, dest)

df = pd.DataFrame({'doc_id': [1, 2, 3,4,5,6,7,8],
                   'paths': ['path1', 'path2', 'path3', 'path4', 'path5', 'path6', 'path7', 'path8'],
                   'colA': ['value1', 'value2', 'value3', 'value1', 'value2', 'value3', 'value1', 'value2'],
                   'colB': ['value8', 'value9', 'value10', 'value11', 'value12', 'value13', 'value14', 'value15'],
                   'colC': ['othervalues1', 'othervalues2', 'othervalues3', 'othervalues4', 'othervalues5', 'othervalues6', 'othervalues7', 'othervalues8']
                   })
#you could use '\\' or '/' for delimiting folder, move calls shutil.move
df.apply(lambda row: move(row['paths'] + '\\doc' + str(row['doc_id']),
                          row['colA'] + '\\' + row['colB'] + '\\' + row['colC'] + '\\' + 'doc' + str(row['doc_id'])), axis=1)

Upvotes: 2

RobinFrcd
RobinFrcd

Reputation: 5486

Here is a solution that should work on every OS (assuming all destination folders are already created):

import os
import shutil
import pandas as pd

for _, row in df.iterrows():
    # Assuming filename is included in paths column
    # Otherwise, the filename should be added to new_path
    # and the shutil.move
    new_path = os.path.join(
        row['colA'], row['colB'], row['colC'],
        os.path.basename(row['paths'])
    )

    shutil.move(row['paths'], new_path)

Upvotes: 2

Related Questions