-2

I would like to check the file by its name and copy from the src_dir to dest_dir in their respective folders if that file is not present in dest_dir.

For example, I have a

src_dir

  • firstfolder
    • file1
    • file3
    • file4
  • secondfolder
    • file1
    • file2
  • anotherfolder
    • file1.txt
    • file2.txt

dest_dir

  • firstfolder

    • file1
    • file2
  • secondfolder

    • file1
  • athirdfolder

  • anotherfolder

    • file.txt

The result should be ,

dest_dir

  • firstfolder

    • file1
    • file2
    • file3
    • file4
  • secondfolder

    • file1
    • file2
  • athirdfolder

  • anotherfolder

    • file.txt
    • file1.txt
    • file2.txt
Charanya G
  • 5
  • 1
  • 4
  • 4
    Please post the code that you already tried (minimized so that it works without other things that aren't related) So we can help you better. Please take a look at: https://stackoverflow.com/help/how-to-ask – Uber Nov 11 '19 at 13:37

1 Answers1

2

Partially answered here.

import os
from shutil import copyfile

filename = 'file.ext'
src_dir = 'src/'
dst_dir = 'dst/'

if not os.path.isfile(dst_dir + filename):
   copyfile(src_dir + filename, dst_dir + filename)

If you wish to do so for each file in a directory :

import os
from shutil import copyfile
import glob

src_dir = 'src/'
dst_dir = 'dst/'

for file_path in glob.glob(os.path.join(src_dir, '*')):
    filename = os.path.basename(file_path)
    if os.path.isfile(file_path) and not os.path.isfile(dst_dir + filename):
        copyfile(file_path, dst_dir + filename)
Donshel
  • 563
  • 4
  • 13
  • Thank you for the solution. I tried this, But it always gives the foldername and not the file name. – Charanya G Nov 12 '19 at 16:38
  • For nested directories, you may use a recursive approach. Or if you know the depth of the directories, hard-code it. For example, you could check if `file_path` is a directory with `os.path.isdir` and if it's the case start the same protocol (`for sub_file in glob.glob(os.path.join(file_path, '*')` ...). – Donshel Nov 12 '19 at 21:03