用变量打开文件

时间:2016-04-29 19:25:04

标签: python file

我尝试根据用户输入的输入打开文件。

这是我现在的代码,但它似乎总是直接进入except块,即使我输入了正确的文件名。

filename = input("Enter a filename: ")

try:
    open(filename.txt, "w")
    print("Succesfully opened", filename,".txt")

except:
    print("File cannot be found.")

任何帮助将不胜感激!

3 个答案:

答案 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不是字符串,所以最简单的解决方案是将文件名与扩展名连接起来。