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>The reason why it's only the last file that could be copied (if it was) is because in this line:</p>

<pre><code>     if file in rowDict[1]:
</code></pre>

<p>you are referencing <code>rowDict</code> outside of the first for-loop. So at that execution moment, it contains the last value of this loop.</p>

<p>If I understand correctly what you are trying to do you could try something like this (untested code):</p>

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

dir_src = 'C:\\Users\\Willie\\Desktop\\Suppliers Dropship\\hunting\\'
dir_dst = 'C:\\image\\' 

with open('shuttle_image.csv', 'r') as f:
    reader = csv.reader(f, delimiter = ',')
    for rowDict in reader:
        id, filename = rowDict
        src_file = os.path.join(dir_src, filename)
        if os.path.exists(src_file):
            shutil.move(src_file, dir_dst)
</code></pre>

<p>So instead of:</p>

<ol>
<li><p>Constructing a dictionary with all the values in your CSV file </p></li>
<li><p>Somehow check for every file in your source directory that it is included in your dictionary (which is what I interpreted you were trying to do) </p>

<ul>
<li>And move it if it does.</li>
</ul></li>
</ol>

<p>You could:</p>

<ol>
<li>For every file extracted from your CSV, check that it exists in your source directory. 

<ul>
<li>If it does, you move it to the destination directory.</li>
</ul></li>
</ol>

<p>Is that what you were trying to doÂ ?</p>

<p>[And if the filename stays the same, you only need to specify the destination directory for the second argument of shutil.move()]</p>

python csv