fastbook icon indicating copy to clipboard operation
fastbook copied to clipboard

Cleaner in lesson 2 moves files to other directories, but files with the same names are there

Open surak opened this issue 2 years ago • 1 comments

Explained here: https://youtu.be/5L3Ao5KuCC4?t=957

This little code snipped can move files to a different category, but as the bears are all numbered files, it will try to move a bear from one directory to another, only to find a file with the same name there.

Like this:

#hide
for idx in cleaner.delete(): cleaner.fns[idx].unlink()
for idx,cat in cleaner.change(): shutil.move(str(cleaner.fns[idx]), path/cat)
---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
/tmp/ipykernel_1936765/2365969314.py in <module>
      1 #hide
      2 for idx in cleaner.delete(): cleaner.fns[idx].unlink()
----> 3 for idx,cat in cleaner.change(): shutil.move(str(cleaner.fns[idx]), path/cat)

/easybuild/2020/software/Python/3.8.6-GCCcore-10.2.0/lib/python3.8/shutil.py in move(src, dst, copy_function)
    784         real_dst = os.path.join(dst, _basename(src))
    785         if os.path.exists(real_dst):
--> 786             raise Error("Destination path '%s' already exists" % real_dst)
    787     try:
    788         os.rename(src, real_dst)

Error: Destination path 'bears/black/00000059.png' already exists

surak avatar Dec 11 '21 15:12 surak

Had the same problem, a bit better code snippet;

for idx in cleaner.delete(): 
    try:
        cleaner.fns[idx].unlink()
    except:
        pass
for idx,cat in cleaner.change():
    print(str(path/cat)+'/moved-'+str(cleaner.fns[idx].name))
    shutil.move(str(cleaner.fns[idx]), str(path/cat)+'/moved-'+str(cleaner.fns[idx].name))

tg44 avatar Jun 06 '22 16:06 tg44