[英]Converting batch folder creation script into python
我正在制作一個python程序,它將某些文件夾移動到不同的目錄中。 目前,我正在使用效果很好的舊批處理腳本-但我想知道如何在python中而不是批處理中執行這些確切的操作,因此我不必調用.bat文件。 最終,我想將其全部合並為一個.py並從中創建一個.exe。
這個腳本移動了一些文件(我的python輸出到notes.txt文件)
for /F "delims=" %%a in (notes.txt) do robocopy /s /MOVE "C:\Users\koka\Documents\Python Scripts\%%a" "C:\Users\koka\Desktop\OUTPUT\%%a\Notes"
pause
然后此腳本將移動其余文件:
dir /b /ad > modmovelist.txt
for /F "delims=" %%a in (modmovelist.txt) do robocopy /s /MOVE
"C:\Users\koka\Documents\Python Scripts\%%a" "C:\Users\koka\Desktop\OUTPUT\%%a\Mods"
最后,此腳本將返回所有文件夾並進行清理,並在每個“ %% a”下添加我想要的所有缺少的文件夾。
set homepath=C:\Users\koka\Desktop\Basics
FOR /f "tokens=*" %%G in ('dir /ad /b "%homepath%\*"') DO (
if not exist "%homepath%\%%G\Emails" mkdir "%homepath%\%%G\Emails"
)
FOR /f "tokens=*" %%G in ('dir /ad /b "%homepath%\*"') DO (
if not exist "%homepath%\%%G\Notes" mkdir "%homepath%\%%G\Notes"
)
FOR /f "tokens=*" %%G in ('dir /ad /b "%homepath%\*"') DO (
if not exist "%homepath%\%%G\Mods" mkdir "%homepath%\%%G\Mods"
)
程序按照上面列出的順序執行。 讓我大跌眼鏡的是,我找不到如何解釋“ %% a”的原因-這會是另一個for循環嗎? 也必須有一個干凈的解決方案來復制dir命令。
如何將所有這些轉換為純python?
嘗試單獨使用“ glob”和“ shutil”查找“ os”方法。 這些方法將允許您瀏覽計算機的dir系統並使用文件進行操作。 您必須導入它們才能像這樣使用它們:import os,import shutil,import glob。
您可以使用shutil.move(src, dst)
將文件或目錄src
遞歸移動到另一個位置dst
。
例如,您的第一個腳本可以寫為:
#!/usr/bin/python
import shutil
# Read from notes file
notes = open("notes.txt").read().splitlines()
# Loop through notes file
for n in notes:
shutil.move("Python Scripts/" + n, "OUTPUT/" + n + "/Notes")
您的第二個批處理腳本看起來本質上是相似的,因此請在此之后對其進行建模。
對於最后一個批處理腳本,每個動作不需要三個單獨的for循環。 而是將所有動作合為一體:
set homepath=C:\Users\koka\Desktop\Basics
FOR /f "tokens=*" %%G in ('dir /ad /b "%homepath%\*"') DO (
if not exist "%homepath%\%%G\Emails" mkdir "%homepath%\%%G\Emails"
if not exist "%homepath%\%%G\Notes" mkdir "%homepath%\%%G\Notes"
if not exist "%homepath%\%%G\Mods" mkdir "%homepath%\%%G\Mods"
)
至於python,您可以這樣做:
#!/usr/bin/python
import os
homepath = "Basics"
# Just get the directories within the homepath
directories = next(os.walk(homepath))[1]
for d in directories
if not os.path.exists(homepath + "/" + d + "/Emails")
os.mkdir(homepath + "/" + d + "/Emails")
if not os.path.exists(homepath + "/" + d + "/Notes")
os.mkdir(homepath + "/" + d + "/Notes")
if not os.path.exists(homepath + "/" + d + "/Mods")
os.mkdir(homepath + "/" + d + "/Mods")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.