简体   繁体   English

Python shutil.move() 函数

[英]Python shutil.move() Function

So i programmed a little GUI to Control some codes i have written recently and i have two tkinter buttons that both have asigned a shutil.move() function.所以我编写了一个小 GUI 来控制我最近编写的一些代码,我有两个 tkinter 按钮,它们都指定了一个 Shutil.move() 函数。 when i click one button, it moves everything to the folder i want it to be in. After clicking the other button it should move the files back to the other folder but it doesnt move them and just gives me the print output, but not the print output in else so its definetly in the if statement当我单击一个按钮时,它会将所有内容移动到我希望它所在的文件夹中。单击另一个按钮后,它应该将文件移回另一个文件夹,但不会移动它们,只会给我打印输出,而不是在 else 中打印输出,因此它在 if 语句中明确

heres my code继承人我的代码

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 is a path and Stop aswell that i create like this Post 是一个路径,Stop 也是我这样创建的

Post = path + "/Post"
Stop = path + "/Stop"

the path variable is selected within the gui and is then saved in a file.在 gui 中选择路径变量,然后将其保存在文件中。

file_post and file_stop are created here file_post 和 file_stop 在此处创建

file_post = os.listdir(path + "/Post")
file_stop = os.listdir(path + "/Stop")

os.listdir returns a static list of the files that are in the directory, not a live view. os.listdir返回目录中文件的静态列表,而不是实时视图。 You won't see the list change after the files have been moved:移动文件后,您将看不到列表更改:

>>> file_stop
['myfile1.txt', 'myfile2.txt']
>>> startbot()
... 
>>> file_stop
['myfile1.txt', 'myfile2.txt']

Therefore, you should generate the list of files as needed by placing os.listdir in the functions as part of the for-loop:因此,您应该根据需要通过将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM