[英]Python shutil.move() Function
所以我編寫了一個小 GUI 來控制我最近編寫的一些代碼,我有兩個 tkinter 按鈕,它們都指定了一個 Shutil.move() 函數。 當我單擊一個按鈕時,它會將所有內容移動到我希望它所在的文件夾中。單擊另一個按鈕后,它應該將文件移回另一個文件夾,但不會移動它們,只會給我打印輸出,而不是在 else 中打印輸出,因此它在 if 語句中明確
繼承人我的代碼
def startbot():
global BOT
print("Start bot pressed")
if BOT == "OFF":
print("Bot is off")
for filename in file_stop:
shutil.move(os.path.join(Stop, filename), Post)
BOT = "ON"
print("BOT:", BOT)
else:
print("Bot is already active.")
def stopbot():
global BOT
print("Stop bot Pressed")
if BOT == "ON":
print("Bot is on")
for file_name in file_post:
shutil.move(os.path.join(Post, file_name), Stop)
BOT = "OFF"
print("BOT:", BOT)
else:
print("Bot is already inactive.")
Post 是一個路徑,Stop 也是我這樣創建的
Post = path + "/Post"
Stop = path + "/Stop"
在 gui 中選擇路徑變量,然后將其保存在文件中。
file_post 和 file_stop 在此處創建
file_post = os.listdir(path + "/Post")
file_stop = os.listdir(path + "/Stop")
os.listdir
返回目錄中文件的靜態列表,而不是實時視圖。 移動文件后,您將看不到列表更改:
>>> file_stop
['myfile1.txt', 'myfile2.txt']
>>> startbot()
...
>>> file_stop
['myfile1.txt', 'myfile2.txt']
因此,您應該根據需要通過將os.listdir
放在函數中作為 for 循環的一部分來生成文件列表:
def startbot():
...
if BOT == "OFF":
print("Bot is off")
for file_name in os.listdir(Stop):
shutil.move(os.path.join(Stop, file_name), Post)
BOT = "ON" # Move this out of for-loop
print("BOT:", BOT)
...
def stopbot():
...
if BOT == "ON":
print("Bot is on")
for file_name in os.listdir(Post):
shutil.move(os.path.join(Post, file_name), Stop)
BOT = "OFF" # Move this out of for-loop
print("BOT:", BOT)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.