I am trying to get my program to read a list of names from a file (say .txt), then search for those in a selected folder and copy and paste those files to another selected folder. My program runs without errors but does not do anything:
Code - updated:
import os, shutil
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
filePath = filedialog.askopenfilename()
folderPath = filedialog.askdirectory()
destination = filedialog.askdirectory()
filesToFind = []
with open(filePath, "r") as fh:
for row in fh:
filesToFind.append(row.strip())
#Added the print statements below to check that things were feeding correctly
print(filesToFind)
print(folderPath)
print(destination)
#The issue seems to be with the copy loop below:
for target in folderPath:
if target in filesToFind:
name = os.path.join(folderPath,target)
print(name)
if os.path.isfile(name):
shutil.copy(name, destination)
else:
print ("file does not exist", name)
print(name)
Update - runs without errors but does not move any files.
Code that works -
import os
import shutil
from tkinter import *
from tkinter import filedialog
root = Tk()
root.withdraw()
filePath = filedialog.askopenfilename()
folderPath = filedialog.askdirectory()
destination = filedialog.askdirectory()
# First, create a list and populate it with the files
# you want to find (1 file per row in myfiles.txt)
filesToFind = []
with open(filePath, "r") as fh:
for row in fh:
filesToFind.append(row.strip())
# Had an issue here but needed to define and then reference the filename variable itself
for filename in os.listdir(folderPath):
if filename in filesToFind:
filename = os.path.join(folderPath, filename)
shutil.copy(filename, destination)
else:
print("file does not exist: filename")
Note - Need to included the file extension in the file being read. Thanks to @lenik and @John Gordon for the help getting there! Time to refine it to make it more userfriendly