我可以在主功能中添加多少功能?

2024-09-30 22:25:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个自动化工具来添加和删除目录,并以字节为单位检查文件的大小。在我编写完所有函数之后,当我在主函数中调用它们时,我要么得到一个错误,要么根本没有提示。我的目标是能够选择一个与您想要使用的工具相关的数字

#!/usr/bin/env python3
import os
import shutil

print ("Welcome to my automation tool.")

user_response = input("""Choose a number that correlates with the tool you wish to use
            1. Remove a directory
            2. Add a directory
            3. Find a file size in bytes

Option: """)

if user_response == "1":
    def rmDir(delDir):
        if os.path.isdir(delDir) == True:#Check whether or not the directory path exists, using the stored variable 'delDir'
        delDir = input("Enter the directory to be removed: ")
        print ("Directory Exists. Deleting now...")
        shutil.rmtree(delDir) #Removes an entire directory
    else:
        print (delDir, "Doesn't exist. Please try again.")

if user_response == "2":
    def newDir(addDir):
        if os.path.isdir(addDir) == True:
            addDir = input("Enter the directory to be created: ")
            print ("Directory already exists.")
        else:
            print ("Creating new directory ",addDir)
            os.makedirs(addDir)

def main():
    delDir = input("Enter the directory to be removed: ")
    rmDir(delDir)
    newDir(addDir)
    addDir = input("Enter the directory to be created: ")

if __name__ == "__main__":
    main()

Tags: thetopathinputifosresponsedef
2条回答

在main()函数中定义addDir之前使用addDir,addDir是一个局部变量,而不是全局变量。另外,确保您是直接运行程序,而不是从另一个文件运行程序(这显然是if “__name__” == __main__

您应该将定义移到if条件之外,并将调用放入if条件中

在main中,您应该放置if条件和input()

如果您想重复执行程序更多次,可以使用while循环

相关问题 更多 >