Python: 将文件复制到根据文件名设置的位置

Python: Copy files to set locations depending on their name

我目前正在制作一个 Disocrd 机器人,它的一个特点是更新速度非常快(以最大限度地减少停机时间)。为此,在重启脚本中,我们有代码检查 USB 是否已挂载,如果已挂载,则需要将其上的文件移至 bots 文件夹,然后更新 bot。

async def cmd_restart(self, channel):
    await self.safe_send_message(channel, ":wave:")
    await self.disconnect_all_voice_clients()
    if os.path.exists(/dev/[usb ID]/Update.zip):
        zip_ref = zipfile.ZipFile(/dev/[usb ID]/Update.zip, 'r')
        zip_ref.extractall(/root/MusicBot/musicbot)
        zip_ref.close()
    raise exceptions.RestartSignal

问题是,随着 bot 的增长,文件已迁移到多个文件夹中,而此脚本不再执行此任务。 我们需要将文件提取到不同的位置,具体取决于它们的名称。

例如 'bot.py' 会进入 musicbot 文件夹,而 config.ini 会进入 config 文件夹,它们都会替换文件夹中的对应项。

由于机器人的性质,不会使用它创建新文件,只会替换现有文件。

原谅我啰嗦,感觉解释起来太复杂了。

首先,您需要获取所有文件名的列表。然后你可以检查那些并将文件放在它们各自的目录中。

应该看起来像这样:

import os
import shutil

async def cmd_restart(self, channel):
    await self.safe_send_message(channel, ":wave:")
    await self.disconnect_all_voice_clients()
    if os.path.exists("/dev/[usb ID]/Update.zip"):
        zip_ref = zipfile.ZipFile("/dev/[usb ID]/Update.zip", 'r')
        zip_ref.extractall("/root/MusicBot/musicbot/tmpExtract")
        zip_ref.close()
        files = os.listdir("/root/MusicBot/musicbot/tmpExtract") # get a list of all files that were in the zip
        for filename in files:   #check every file 
            if (filename == "meetsYourCondition.conf"):
                shutil.move("/root/MusicBot/musicbot/tmpExtract/meetsYourCondition.conf", "/root/MusicBot/musicbot/DirectoryYouWantItToGoTo")
            #elif (filename == "meetsYourNextCondition.conf"):
            #...
            # you get the idea
    raise exceptions.RestartSignal

当我想要 运行 机器人时遇到问题,它不起作用,它对我说:

SyntaxError: Unexpected token '??='
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at Object.<anonymous> (C:\Users\Altamimi\Desktop\bot\node_modules\discord.js\src\rest\RESTManager.js:4:20)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)