how to detect removable devices and assign it as the source it order to copy file from it using python?

125 views Asked by At

I have a python script that first detect removable devices and then copy files from this removable device to a new destination.

I have created a function to detect removable devices and a second function to copy from files.

but the problem i do not know how to make the detected device as the source for the copy function.

For now i am hard coded the source but its not a good practice.

code:

import win32api
import win32file

import calendar
import os
import shutil
from os import path
from datetime import date

def main():
    detectUSB()
    copy()

def detectUSB():
    # Returns a list containing letters from removable drives
    drive_list = win32api.GetLogicalDriveStrings()
    drive_list = drive_list.split("\x00")[0:-1]  # the last element is ""
    list_removable_drives = []
    for letter in drive_list:
        if win32file.GetDriveType(letter) == win32file.DRIVE_REMOVABLE:# check if the drive is of type removable 
            list_removable_drives.append(letter)
    print("list drives: {0}".format(letter))
    return list_removable_drives

src = "I:\\" ## this is where i hardcoded the source 

def copy():

    try:
        for dirpath, dirnames, files in os.walk(src):

            print(f'Found directory: {dirpath}')
            # for file_name in files:
            if len(dirnames)==0 and len(files)==0:
                    print("this directory is empty")
            else:
                print(files)
    except Exception as e:
        print(e)
if os.path.exists(dst): 
        shutil.rmtree(dst)
        print("the deleted folder is :{0}".format(dst))
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))
    else:
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))

if __name__=="__main__":
    main()

so i want to make the return variable of the detectUSB() function as a argument the src for the copy() function.

1

There are 1 answers

0
Dev Dj On

i fixed the problem by returning the variable of the detectUSB() function and then assign it to the copy () function with adding the argument to the copy() function as below:

in the main function

copy(detectUSB())

in the copy function

def copy(src)
        for dirpath, dirnames, files in os.walk(src):