在Python中检查输入文件是否存在

1 投票
1 回答
1686 浏览
提问于 2025-04-17 22:27

我正在写一个函数,这个函数会读取一个已经处理过的文件(file_name)。在这个处理过的文件(open_file1)中,所有的行都是元组。我的问题是这样的:为了使用这个程序,我必须总是先输入命令,然后再输入文件名。如果用户直接输入“团队标识符”(也就是第三个elif语句),而没有先输入文件名,那么程序就会崩溃。因此,我在第三个elif语句中用一个os语句检查输入文件是否存在。如果输入文件不存在,我就写了一个else语句,提示用户输入另一个命令(也就是输入文件名,然后重新开始)。但是,不知道为什么,当我输入“团队标识符”命令时,程序没有执行第三个elif语句的else部分。有没有什么建议?谢谢!

 def main():
    command=input('Input cmd: ')
    while command.lower() !='quit':
        if command.lower()=='help':
            print("QUIT\n"\
                  "HELP\n"\
                  "INPUT filename\n"\
                  "TEAM identifier\n"\
                  "REPORT n HITS\n"\
                  "REPORT n BATTING\n"\
                  "REPORT n SLUGGING\n")
        elif command.startswith('INPUT') and len(command)>6:
            file_name=str(command[6:])
            open_file1=new_list(file_name)
            print(open_file1)

        elif command.startswith('TEAM') and len(command)>5:
            if os.path.isfile(open_file1):
                team_name=str(command[4:])
                for line in open_file1:
                    print(line[1])

            else:
                command=input('Input cmd: ')

        command=input('Input cmd: ')
main()

错误信息:

Traceback (most recent call last):
  File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project 07\openfile.py", line 98, in <module>
    main()
  File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project   07\openfile.py", line 81, in main
    if os.path.isfile(open_file1):
UnboundLocalError: local variable 'open_file1' referenced before assignment

1 个回答

0

问题出在你这一行 os.path.isfile(open_file1)。这个 isfile 函数是需要一个字符串作为输入,但你给它的是一个文件对象(如果 open_file1 存在的话),或者是一个没有被引用的变量(如果 open_file1 不存在的话)。

我建议把这个 if-else 语句换成一个 try-except 块:

elif command.startswith('TEAM') and len(command)>5:
            try:
                team_name=str(command[4:])
                for line in open_file1:
                    print(line[1])

            except UnboundLocalError:
                command=input('Input cmd: ')

撰写回答