Rabu, 25 Mei 2022

Python - Transfer File From Different Folder While Skip Duplicate

 

Problem

Another day, my boss request me :

Can you make me a python script to move all file in "this" folder to "that" folder, so i can automate backup "this" folder, you can skip duplicate files to shorten process time


Logic

We can loop through all files in "this" folder, and check if is in "that" folder. If isn't in "that" folder, we use function "shutil.copy2" to move files to "that" folder. (We use copy2 because we want to preserve file metadata)

1. import library function "shutil" and "os"
2. Record path to "this" folder to variable "fromDirectory"
3. Record path to "that" folder to variable "toDirectory"
4. Loop trough all files, and check with function "os.path.isfile"
5. Use function "shutil.copy2" to move if check is done
6. save python script in any folder you want
7. create task schedule for automate


Solution

Make new python with the following script :

import os
import shutil

fromDirectory = "'this' folder path"
toDirectory = "'that' folder path"

src_files = os.listdir(fromDirectory)
for file_name in src_files:
    full_file_name_src = os.path.join(fromDirectory, file_name)
    full_file_name_des = os.path.join(toDirectory, file_name)
    if not (os.path.isfile(full_file_name_des)):
        if (os.path.isfile(full_file_name_src)):
            shutil.copy2(full_file_name_src, toDirectory)

save script, and make task schedule to autorun script

Sabtu, 19 Maret 2022

Python - Transfer File From Different Folder And Replace Same File

Problem

One day, my boss request me :

Can you make me a python script to move all file in "this" folder to "that" folder, so i can automate backup "this" folder and the code must replace file with same name to "that" folder


Logic

We can use function "copy_tree", because that script will move all file and subfolder in specified folder and the function will replace same file

1. import library function "copy_tree"
2. Record path to "this" folder to variable "fromDirectory"
3. Record path to "that" folder to variable "toDirectory"
4. Use function "copy_tree" to move and replace file with same name
5. save python script in any folder you want
6. create task schedule for automate


Solution

Make new python with the following script :

from distutils.dir_util import copy_tree

fromDirectory = "'this' folder path"
toDirectory = "'that' folder path"

copy_tree(fromDirectory, toDirectory)

save script, and make task schedule to autorun script

Python - Transfer File From Different Folder While Skip Duplicate

  Problem Another day, my boss request me : Can you make me a python script to move all file in "this" folder to "that" ...