Skip to main content
 首页 » 编程设计

python之尝试逐步完善我的代码,提示 python 中的用户输入文件

2025年04月02日9jyk

对于第一部分,提示用户输入包含关键字的文件的名称,检查以确保该文件存在,如果不存在,我的程序应生成异常并退出。这部分我做对了吗?

done = False 
    while not done: 
        try: 
            keywords = input("Enter file named keywords.txt: ") 
            infile = open(keywords, "r") 
            done = True 
        except IOError : 
            print("Error: file not found.") 
            exit() 
        try: 
            tweets = input("Enter file named tweets.txt: ") 
            infile = open(tweets, "r") 
            done = True 
        except IOError : 
            print("Error: file not found.") 
            exit() #Should exit if doesnt exist? Doesnt say in assignment 

忽略#statement 哈哈

请您参考如下方法:

好的。我认为它应该是这样的:

try: 
    file_path = input("Enter file named keywords.txt: ") # don't call it keywords, cause it is not 
    with open(file_path, "r") as infile: #this will open a file and close it when needed  
        #do what you need to do with your file 
except IOError : # it will catch exception if file not found 
    print("Error: file not found.") 
    exit()