Python实现自动在磁盘中新建文件夹,并将指定文件复制到对应目录

科技   2024-09-27 16:17   广东  

应用场景:

领导让我升级四十个RTK的主机固件,需要手动新建文件夹将升级文件放置在文件夹内,然后重启即可

import win32fileimport win32eventimport win32conimport shutilimport os
def detect_usb_drive(): drive_list = [] drivebits = win32file.GetLogicalDrives() for d in range(1, 26): mask = 1 << d if drivebits & mask: drname = '%c:\\' % chr(ord('A') + d) t = win32file.GetDriveType(drname) if t == win32file.DRIVE_REMOVABLE: drive_list.append(drname) return drive_list
def copy_files(source_folder, target_folder, filenames): try: if not os.path.exists(target_folder): os.makedirs(target_folder) for filename in filenames: source_file = os.path.join(source_folder, filename) target_file = os.path.join(target_folder, filename) if os.path.exists(source_file): shutil.copy(source_file, target_file) return True except Exception as e: return False
def main(): source_folder = r'C:\Users\zheyu\Desktop\固件' while True: drives = detect_usb_drive() for drive in drives: u_drive_folder = os.path.join(drive, 'FW') copy_success = copy_files(source_folder, u_drive_folder, ['A3.bin', 'A3Boot.bin']) if copy_success: print(f"文件成功复制到 {u_drive_folder}。") else: print(f"复制文件到 {u_drive_folder} 时出现错误。错误信息:{str(e)}") temp_folder = os.path.join(drive, 'temp') os.makedirs(temp_folder) copy_success_temp = copy_files(source_folder, temp_folder, ['A3.bin']) if copy_success_temp: print(f"文件成功复制到 {temp_folder}。") else: print(f"复制文件到 {temp_folder} 时出现错误。错误信息:{str(e)}") win32event.WaitForSingleObject(win32event.CreateEvent(None, 0, 0, None), 1000)
if __name__ == '__main__': main()

使用方法

固件地址为C:\Users\zheyu\Desktop\固件

该程序需使用管理员权限,管理员权限打开CMD,cd至程序所在目录cd C:\Users\zheyu\Desktop,python运行该程序python your_file_name.py,your_file_name为python文件名称

当然以上是调试代码时候用的,没问题后直接打包成exe文件


点点GIS
一点GIS,一点Python,一点杂谈
 最新文章