- 1 year ago
How to use Python to identify Usb drives and use them as Destination paths for copying files and directories
You can use the psutil
library in Python to identify USB drives and then use the shutil
library to copy files and directories to the identified USB drives. Here's a step-by-step guide on how to do it:
Install the required libraries:
pip install psutil
Import the required modules:
pythonimport os
import psutil
import shutil
Define a function to check if a path is a removable drive (USB drive):
pythondef is_removable_drive(path):
drive_type = psutil.disk_partitions(all=True)
return any(drive.device == path and 'removable' in drive.opts for drive in drive_type)
Find all available drives and filter for removable drives (USB drives):
pythondef get_usb_drives():
drives = psutil.disk_partitions(all=True)
usb_drives = [drive.mountpoint for drive in drives if is_removable_drive(drive.device)]
return usb_drives
Copy files and directories to USB drives:
pythondef copy_to_usb(src_path, dst_path):
usb_drives = get_usb_drives()
if dst_path not in usb_drives:
print("Destination path is not a USB drive.")
return
try:
shutil.copytree(src_path, os.path.join(dst_path, os.path.basename(src_path)))
print("Files and directories copied successfully.")
except Exception as e:
print("Error copying files and directories:", e)
Call the
copy_to_usb()
function with the source and destination paths:pythonsrc_path = "path/to/source"
dst_path = "path/to/destination"
copy_to_usb(src_path, dst_path)
Make sure to replace "path/to/source"
and "path/to/destination"
with the actual paths you want to use. Also, note that this code assumes that you have the necessary permissions to access the source and destination paths.
Remember that when dealing with USB drives, it's crucial to handle errors and exceptions gracefully, as removable drives may be disconnected at any time.