views:

96

answers:

3

Hi, I am trying to have a file path like 'C:\Programfiles\file.txt' but i would like to have file.txt be a variable that i can change whenever i need to. I am trying to compare 2 directories then copy files from one to another if they arent already there. i have this code so far.

import os
import shutil
A= set(os.listdir(r"C:\Users\Morpheous\Desktop\Python Test"))
B= set(os.listdir(r"C:\Users\Morpheous\Desktop\Python Test 2"))
if len(A)< len(B):
    C=B-A
    print("File is: %s" %(C))
    shutil.copy2('C:\\Users\\Morpheous\\Desktop\\Python Test 2\\%r'%(C),'C:\\Users\\Morpheous\\Desktop\\Python Test')

elif len(A) > len(B):
    C=B-A
    print(C)

and i get an error because the variable is inserted into path with {''} around it. How would i go about doing this?

A: 

Use %s instead of %r, and C.pop().replace(' ', '\\ ') instead of C, which is a set and not a string (the replace is needed to "escape" every space -- I think). Last but not least, I think you're using shutil.copy2 wrong: see the docs -- it wants two arguments, not one argument with a space separator.

There may well be other bugs lurking in your code (I'm not sure what that 2\\ part is supposed to mean, for example; and you may need a loop, as copy2 does one file at a time and you may have serveral; etc, etc), but these at least are definitely there.

Alex Martelli
Thanks Guys! that helped alot, im new to python so still gettin the ins and outs.
Morpheous
+3  A: 

Please use os.path.join to construct paths. Also, you should put the directories in variables for reuse. Furthermore you need to iterate over the difference between the folders (B - A) in order to get each filename that's in the difference set (C is the set of files that have been added!).

Here's the corrected version - tested and working:

import os
import shutil

pathA = r"C:\Users\Morpheous\Desktop\Python Test"
pathB = r"C:\Users\Morpheous\Desktop\Python Test 2"

A = set(os.listdir(pathA))
B = set(os.listdir(pathB))
C = B - A

if len(C):
    print("Difference is: %s" % repr(C))

    for addedFile in C:
        shutil.copy2(os.path.join(pathB, addedFile),
                     os.path.join(pathA, addedFile))
else:
    print("No new files")
AndiDog
len(A) > len(B) doesn't ensure that C is empty. You should compute C always and then simply check if it is empty for the purposes of reporting.
@rgrig: Good point, changed that in my code.
AndiDog
+2  A: 

you should use a library like filecmp to compare directories/files

>>> import filecmp
>>> import os
>>> dira = os.path.join("/home","dir1")
>>> dirb = os.path.join("/home","dir2")
>>> os.listdir(dira)
['file.jpg', 'file2.txt']
>>> os.listdir(dirb)
['file1.jpg', 'file2.txt']
>>> r=filecmp.dircmp(a,b)
>>> r.right_only  # only in dirb
['file1.jpg']
>>> r.left_only   # only in dira
['file.jpg']
ghostdog74