Search code examples
pythonpandasdataframeglob

How to copy specific files, those contained on the dataframe, from one folder to another


I have the following dataframe:

import pandas as pd
df_Sensor = pd.DataFrame({'Name_Archive': ['SENSOR_1', 'SENSOR_250'], 
                                  'Type': ['Analog', 'Dig'],
                                  'Value': [199, 0]})

I have two folders on my desktop. First the "Archive" folder that has the csv files with names:

SENSOR_1.csv
SENSOR_198.csv
SENSOR_250.csv

(its location is: C:/Users/User/Desktop/Archive)

The other folder is called "Archive_Select", this folder is empty. (its location is: C:/Users/User/Desktop/Archive_Select)

I would like to go through the 'Name Archive' dataframe column and make a copy of that file, which is in the (Archive) folder in the new folder (Archive_Select).

For example, as the 'Name_Archive' column contains the name of 2 of my files in the 'Archive' folder, I would like that when I open the 'Archive_Select' folder, only the files would appear:

SENSOR_1.csv #and 
SENSOR_250.csv

I tried to use the glob function, but I don't know how to do what I wanted:

import glob
All_Archives = glob.glob("C:/Users/Usuario/Desktop/Archive/*.csv")

for i in range(0, len(df_Sensor)):
    for j in range(0, len(All_Archive)):
        if(df_Sensor['Name_Archive'].iloc[i] == All_Archive.iloc[j]):
            df_Sensor.to_csv("C:/Users/Usuario/Desktop/Archive_Select.csv")

Solution

  • You first define your source and destination directories

    import pandas as pd
    from shutil import copyfile
    src_directory = "C:\Users\User\Desktop\Archive"
    dest_directory = "C:\Users\User\Desktop\Archive_Select"
    

    Then loop over your desired files from the dataframe to copy them

    for fileName in df_Sensor['Name_Archive']: 
        src_file = src_directory + "\\" + fileName + ".csv"
        dest_file = dest_directory + "\\" + fileName + ".csv"
        copyfile(src_file, dest_file)