python - 如何检测可移动设备并将其分配为使用 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的参数。
解决方案
我通过返回 detectUSB() 函数的变量来解决问题,然后将其分配给 copy() 函数,并将参数添加到 copy() 函数,如下所示:
在主函数中
copy(detectUSB())
在复制功能中
def copy(src)
for dirpath, dirnames, files in os.walk(src):
推荐阅读
- python - 如何运行 python 命令来单击页面上的每个链接并提取每个链接的标题、内容和日期?
- r - R data.table,如何为每个单元格值加1不等于0
- azure - 如何在 Azure SDK 中使用“扩展”参数?
- r - renv - 手动覆盖锁定文件中的包版本
- android - FrameLayout 溢出 CoordinatorLayout 中的窗口
- c - 我的每盎司成本计算有什么问题
- python - 使用 CSV 作为参数进行单元测试
- flutter - Figma 中的字体大小与 Flutter 相比如何?
- java - 通过单击项目开始另一个活动(recyclerview 列表)
- java - Docker IPv6 协议系列不可用