Move files listed in csv file?
<p>I have been trying to use the following code to move files that are listed in a csv list. But at most it will copy the last file in the list but not the rest.
I keep hitting this wall with every example I have seen listed what am I doing wrong?</p>

<p>My CVS list will have a list like: </p>

<pre><code>12355,12355.jpg
</code></pre>

<p>Here's my code</p>

<pre><code>import os
import shutil
import csv
keys={}
with open('shuttle_image.csv', 'r') as f:
 reader = csv.reader(f, delimiter = ',')
 for rowDict in reader:
    keys[rowDict[0]] = rowDict[1]
    print (rowDict)

dir_src = 'C:\\Users\\Willie\\Desktop\\Suppliers Dropship\\hunting\\'
dir_dst = 'C:\\image\\' 
for file in os.listdir(dir_src):
    src_file = os.path.join(dir_src, file)
    dst_file = os.path.join(dir_dst, file)
    if file in rowDict[1]:
        shutil.move(src_file, dst_file)
</code></pre>

<p>I think doing something like this will work (untested):</p>

<pre><code>import os
import shutil
import csv

keys={}
with open('shuttle_image.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for rowDict in reader:
       keys[rowDict[0]] = rowDict[1]
       print(rowDict)  # if desired

valid_files = set(keys.values())  # file names found in csv
dir_src = 'C:\\Users\\Willie\\Desktop\\Suppliers Dropship\\hunting\\'
dir_dst = 'C:\\image\\'
for file in os.listdir(dir_src):
    if file in valid_files:
        src_file = os.path.join(dir_src, file)
        dst_file = os.path.join(dir_dst, file)
        shutil.move(src_file, dst_file)
</code></pre>

<p>As an optimization, unless you need the <code>keys</code> dictionary for other processing, you could change the first part so it just creates the <code>valid_files</code> set variable used in the second <code>for</code> loop:</p>

<pre><code>valid_files = set()  # empty set
with open('shuttle_image.csv', 'r') as f:
    for rowDict in csv.reader(f, delimiter=','):
       valid_files |= {rowDict[1]}  # add file name to set
       print(rowDict)  # if desired
</code></pre>

python csv