简体   繁体   中英

python - How to copy files from one directory to another only if the file is not present in destination?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM