识别U盘并且复制内容到PC以及复制PC指定内容到U盘
1 import win32file
2 import shutil
3
4
5 # 获取到所有的磁盘驱动
6 def get_all_drives():
7 drives = []
8 sign = win32file.GetLogicalDrives()
9 all_drives = ["A:\\", "B:\\", "C:\\", "D:\\", "E:\\", "F:\\", "G:\\", "H:\\", "I:\\",
10 "J:\\", "K:\\", "L:\\", "M:\\", "N:\\", "O:\\", "P:\\", "Q:\\", "R:\\",
11 "S:\\", "T:\\", "U:\\", "V:\\", "W:\\", "X:\\", "Y:\\", "Z:\\"]
12 for i in range(25):
13 if sign & 1 << i:
14 print(win32file.GetDriveType(all_drives[i]))
15 if win32file.GetDriveType(all_drives[i]) >= 1:
16 drives.append(all_drives[i])
17 return drives
18
19
20 ret = get_all_drives()
21 print(ret)
22
23
24 # 判断是否是U盘
25 def get_u_disk(drives):
26 u_disk = []
27 for item in drives:
28 try:
29 free_bytes, total_bytes, total_free_bytes = win32file.GetDiskFreeSpaceEx(item)
30 # 转化成GB
31 if (free_bytes / 1024 / 1024 / 1024) < 32:
32 u_disk.append(item)
33 print('append')
34 else:
35 print(free_bytes / 1024 / 1024 / 1024)
36 except:
37 break
38 return u_disk
39
40
41 lst = get_u_disk(ret)
42
43 # 复制文件夹中的内容到U盘里
44 usb_path = lst[0] + "123\\"
45 pc_path = r"D:\python_project\tools"
46
47
48 def copy_folder_file():
49 shutil.copytree(pc_path, usb_path)
50
51
52 copy_folder_file()
53 # 复制文件到U盘 注意:路径需要存在也即下面的路径必须在U盘上存在名称为123文件夹才行
54 usb_path = lst[0] + "123\\"
55 pc_path = r"D:\exercise\new_exe.rar"
56
57
58 def copy_file():
59 shutil.copy(pc_path, usb_path)
60
61
62 copy_file()