我尝试根据用户输入的输入打开文件。
这是我现在的代码,但它似乎总是直接进入except块,即使我输入了正确的文件名。
filename = input("Enter a filename: ")
try:
open(filename.txt, "w")
print("Succesfully opened", filename,".txt")
except:
print("File cannot be found.")
任何帮助将不胜感激!
答案 0 :(得分:4)
这样可行。
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.")
答案 1 :(得分:2)
将open(filename.txt, "w")
更改为open(filename + '.txt', "w")
答案 2 :(得分:-1)
由@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不是字符串,所以最简单的解决方案是将文件名与扩展名连接起来。