Reputation: 199
I have a folder full of files, such as txt files, csv files, HTML files, pdf files. Then I have another csv file that contains the names of the files that I need from that folder. I want to move the files to another folder that match file names from the csv file "name column".
Sample file names in the folder:
doggy.csv
cattodog.txt
birdy.pdf
eagle.pdf
:
:
wolfy.pdf.txt.csv
My csv file:
ID Name
001 doggy.csv
002 cattodog.txt
003 eagle.pdf
:
:
n wolfy.pdf.txt.csv
I am wondering are there any fast ways to create a code that can loop through the folder that matches the "name column" from my csv file then moves those match files to another folder?
Thanks!
Upvotes: 1
Views: 1813
Reputation: 816
You can first use pandas
to read your csv file containing the filenames and then loop through it:
import pandas as pd
import os, shutil
## read filenames using pandas
df_files = pd.read_csv("csvContainingFilestoMove.csv")
## set file locations
fileOrigin = "./" #file origin
fileDest="destinationPath/" #file destination
for ff in df['Name'].tolist():
print(f"Moving file {ff}")
shutil.move(fileOrigin+ff, fileDest) #shutil to move file
You can also use if not os.path.exists(fileDest+ff)
to check if the file already exists at the destination in case you want to use copy
instead of move
Upvotes: 2
Reputation: 167
This code might help:
import pandas as pd
import shutil
my_csv = pd.read_csv('my_files.csv')
file_names = my_csv.Name.tolist()
for file_name in file_names:
shutil.move("path/to/filesfolder/".join(file_name), "path/to/newfolder/".join(file_name))
Also, I recommend to save your names in a txt file and mv their files with bash.
def save_to_txt(file_list):
with open('file_names.txt', 'w+') as wfile:
for file in file_list:
wfile.write(file + '\n')
and then in your commandline:
for file in $(cat path/to/file_names.txt); do mv path/to/"$file" path/to/newfolder; done
Upvotes: 1