2024-04-24 00:22:49 发布
网友
我正试图根据用户输入的输入打开一个文件。你知道吗
这是我现在的代码,但它似乎总是直接转到except块,即使我输入了正确的文件名。你知道吗
filename = input("Enter a filename: ") try: open(filename.txt, "w") print("Succesfully opened", filename,".txt") except: print("File cannot be found.")
任何帮助都将不胜感激!你知道吗
如@Bharel所示,这将起作用:
filename = input("Enter a filename: ") try: open(filename + ".txt", "w") print("Succesfully opened", filename,".txt") except: print("File cannot be found.")
问题出在open(filename.txt, "w"),因为.txt不是字符串,所以最简单的解决方案是将文件名与扩展名连接起来。你知道吗
open(filename.txt, "w")
将open(filename.txt, "w")更改为open(filename + '.txt', "w")
open(filename + '.txt', "w")
这会有用的。你知道吗
filename = input("Enter a filename: ") try: # Access filename as a variable open(filename + ".txt", "w") print("Succesfully opened", filename,".txt") # Catch the specific exception except IOError: print("File cannot be found.")
如@Bharel所示,这将起作用:
问题出在
open(filename.txt, "w")
,因为.txt不是字符串,所以最简单的解决方案是将文件名与扩展名连接起来。你知道吗将
open(filename.txt, "w")
更改为open(filename + '.txt', "w")
这会有用的。你知道吗
相关问题 更多 >
编程相关推荐