打开带有变量的文件

2024-04-24 00:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图根据用户输入的输入打开一个文件。你知道吗

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

filename = input("Enter a filename: ")

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

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

任何帮助都将不胜感激!你知道吗


Tags: 文件代码用户txtinput文件名openfilename
3条回答

如@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")

这会有用的。你知道吗

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.")

相关问题 更多 >