Kjjassy Kjjassy - 1 year ago 71
Linux Question

Python - How to copy content of USB(Flash) to system directory

What i want to program is,

When USB drive is connected to system the code must initiate automatically and Copy the content(Directories, Files etc.) of usb drive to Default Backup Directory of System.

I have came across some sites and found that I can use shutil library https://docs.python.org/2/library/shutil.html
High-level file operations. I haven't used Shutil Library, So is there any other way to achieve,

has anyone did this before so please help. Thanks

Answer Source

I have fix this and solved, hope this will help to those guys who are beginners like me.

First i code to copy files and directories using shutil for more help https://docs.python.org/2/library/shutil.html, connect usb drive to perform operation

Step 1 : code_to_copy.py

import os
import datetime
import shutil
from shutil import copytree, ignore_patterns

files = os.listdir('/media/user/')

destination = '/home/user/Path/Backup/back_%s'%datetime.datetime.now()
try :
    for f in files:
        source = '/media/user/%s' % f
        copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))    
except Exception as e:
    print e

you can run this file to check whether it is copying or not, then

create bash file

Step 2 : code_to_copy.sh

python /home/user/path/code_to_copy.py

make sure you have permissions to this files

step 3 : add to cron

$ crontab -e

#add this line
* * * * * /home/user/path/code_to_copy.sh > /tmp/code_to_copy.log

# check log file at /tmp/code_to_copy.log

after a minute your connected device data will be copied to your backup folder and hola.