'Trying to copy multiple files in a single directory to directories with matching names

I am developing a file management project for a law office. All case files are in .pdf and reside in a single directory. Any help is greatly appreciated.

My project is as follows:

  1. The first section of my code (1) creates a directory for each case file and (2) copies each case file into the directory with the matching name. No issues there.
  2. The second section of my project is code uses docxtpl and openpyxl to generate settlement agreements for each case file. No issues there.
  3. The final step is to copy the newly generated consent agreements into the appropriate directories that were created in Step 1. This is where I am having problems. The consent agreements are generating, but they are not.

Here is the code so far:

files2 = os.listdir(template_dir)
del files2 [0:2]
print(files2)

#attempt to move consent agreements to directories created in section 1
        
for file in files2:
    if os.path.exists(dir_path):
        shutil.copy(os.path.join(r'template_dir', file), os.path.join(file, dir_path))


Solution 1:[1]

A few things are wrong with the path arguments in the shutil.copy() function.

In the first/source path you have os.path.join(r'template_dir', file). Since template_dir is already a string variable you should not put it in quotes. By putting it in quotes you are sending the text "template_dir" to the os.path.join() function. Corrected version is os.path.join(template_dir, file).

In the second/destination path you flipped the order of the variables. The directory should come first followed by the filename. Corrected version is os.path.join(dir_path, file)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 p_sutherland