moving individual 230 pdf files to already created folders

57 Views Asked by At

@nmnhI'm trying to move over 200 pdf files, each to separate folders that are already created and named 2018. The destination path for each is like- GFG-0777>>2018. Each pdf has an unique GFG-0### name that matches the folders I already created that lead to the 2018 destination folders. Not sure how to iterate and get each pdf into the right folder.... :/

I've tried shutil.move which i think is best but have issues with paths I think.

import os
import shutil


srcDir = r'C:\Complete'
#print (srcDir)
dstDir = r'C:\Python27\end_dir'
dirList = os.listdir(srcDir)
for f in dirList:
    fp = [f for f in dirList if ".pdf" in f] #list comprehension to iterate task (flat for loop)
for file in fp:
    dst = (srcDir+"/"+file[:-4]+"/"+dstDir+"/"+"2018")
    shutil.move(os.path.join(srcDir, dst, dstDir))         

error: shutil.move(os.path.join(srcDir, dst, dstDir)) TypeError: move() missing 1 required positional argument: 'dst'

2

There are 2 best solutions below

2
On

AFAICT you are calling shutil.move(os.path.join(srcDir, dst, dstDir)) without a to. According to the documentation you need to have a from and to folder. https://docs.python.org/3/library/shutil.html#shutil.move

I guess your idea was to somehow create a string containing the dst and src :

dst = (srcDir+"/"+file[:-4]+"/"+dstDir+"/"+"2018")

What you actually want is something along this line:

dst_dir = dstDir+"/"+"2018"
src_dir = srcDir+"/"+file[:-4]
shutil.move(src_dir,dst_dir)

Above code is just for demonstration. If this does not work you could tree or ls -la example a small part of your srcdir and dstdir and we could work something out.

0
On

@nmanh I managed to work it out. Thanks for calling out the issue to create string with src and dst. After removing the string, I tweaked a bit more but found I had too many "file" in code. I had to make two of them "file1" and add a comma in the shutil.move between src and dst. Thanks again

import os
import shutil


srcDir = r'C:\Complete'
#print (srcDir)
dstDir = r'C:\Python27\end_dir'
dirList = os.listdir(srcDir)
for file in dirList:
    fp = [f for f in dirList if ".pdf" in f] #list comprehension to iterate task 
    (flat for loop)
for file in fp:
    if ' ' in file: #removing space in some of pdf names noticed during fp print
    file1 = file.split(' ')[0]# removing space continued
else:
    file1 = file[:-4]# removing .pdf
    final = dstDir+"\\"+file1+"\\2018"
    print (srcDir+"\\"+file1+" "+final)
shutil.move(srcDir+"\\"+file,final)