首页 > 解决方案 > 如何检测可移动设备并将其分配为使用 python 从中复制文件的源?

问题描述

我有一个 python 脚本,它首先检测可移动设备,然后将文件从这个可移动设备复制到新的目的地。

我创建了一个检测可移动设备的功能和一个从文件复制的第二个功能。

但问题是我不知道如何将检测到的设备作为复制功能的来源。

现在我对源代码进行了硬编码,但这不是一个好习惯。

代码:

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()

所以我想将detectUSB()函数的返回变量作为copy () 函数的 src的参数。

标签: pythonshutilremovable-storage

解决方案


我通过返回 detectUSB() 函数的变量来解决问题,然后将其分配给 copy() 函数,并将参数添加到 copy() 函数,如下所示:

在主函数中

copy(detectUSB())

在复制功能中

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

推荐阅读