Python 如何使try循环用于txt文件加载?

Python 如何使try循环用于txt文件加载?,python,Python,但是,当我要求用户输入文档时,我创建了一个代码,将txt文件作为csv引导。编号,我的try循环不会检查文档。相反,它一直在询问文件名。但是,如果我删除第一个If函数(If choice==“”),它就可以工作,稍后我需要该If函数。 代码如下 def menu2(choice1): while True: if choice1=="": choice1=float(input("""\033[1;36;48mNow yo

但是,当我要求用户输入文档时,我创建了一个代码,将txt文件作为csv引导。编号,我的try循环不会检查文档。相反,它一直在询问文件名。但是,如果我删除第一个If函数(If choice==“”),它就可以工作,稍后我需要该If函数。 代码如下

def menu2(choice1):
while True:
    if choice1=="":
        choice1=float(input("""\033[1;36;48mNow you have the following choices:
                          0: Set new directory
                          1: Load data
                          5: Quit
                          
                \033[1;37;48mPlease enter a number: """))
        print()
    elif choice1 == 0:
        menu1()
    elif choice1 == 1:
        print("\033[1;36;48mTo load the data, the data document name needs to be given with "".txt"" at the end")
        choice2=input("""
                \033[1;37;48mPlease enter the name of the document: """)
        print()
        try:
             pd.read_csv(choice2, sep=" ", header=None)
        except:
             print("Error, could not find data in directory. Files in directory is listed below:")
             print(os.listdir(os.getcwd()))
             continue
        menu3("")
    elif choice1 == 5:
        print("Thanks for using the data analysis program, bye")
        break
    else:
        print(red+"Not a valid option, please try again"+white)
        print()
        continue
prevData=pd.read_csv(choice2, sep=" ", header=None)
return prevData

创建一个变量
loop=True
,并将
while True
更改为
while loop
。在try语句中,在读取csv后,您可以使
循环=False
,它将中断循环。

“try loop”
try
不会启动循环。我认为您最好查看一些关于Python的基本教程。很明显,如果。。埃利夫。。else结构,但它不是金锤,也不是所有东西都是钉子。尝试一行一行地逐行遍历代码,跟踪各种变量的值,找出代码为什么会这样做,以及您希望该流程如何更改。如果你没有得到某个特定的部分,问问这个问题——一个广泛的“为什么我的程序不起作用”不是一个很好的问题,因为你不可能得到你需要的答案。