2016-07-26 35 views
0

我目前正在製作一個Disocrd機器人,它的一個功能是非常快速的更新(以最大限度地減少停機時間)。爲此,在重新啓動腳本中,我們有代碼檢查是否掛載了一個usb,如果是,它上面的文件需要移動到bots文件夾中,然後更新bot。Python:根據名稱複製文件以設置位置

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.py'會進入musicbot文件夾,而config.ini會進入config文件夾,並且它們會替換文件夾中的對應文件。

由於bot的特性,不會使用此創建新文件,只會替換現有文件。

請原諒我的散漫,解釋過於複雜。

回答

0

首先,您需要獲取所有文件名的列表。然後你可以檢查這些文件並將它們放在各自的目錄中。

應該是這個樣子:

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 
+0

感謝那些完美地工作 – DNA

相關問題