英文:
opening a python file from input stored in a variable
问题
我正在尝试让我的程序打开并读取一个文本文件,该文件名存储在file_name
变量中,但似乎没有读取任何内容,但会打印“文件现在已打开”。
def open_sn_file(self):
while True:
file_name = input("请输入文件名或输入'done'退出程序:")
if file_name == "done":
print("再见。")
break
try:
with open(file_name, 'r') as file:
file.read()
print("文件现在已打开。")
我尝试了很多方法,仍然遇到相同的问题。我不确定该怎么办。
英文:
I am trying to get my program to open and read a text file from what the user inputs stored in the file_name
variable, but it doesn't seem to read anything, but does print "File is now open".
def open_sn_file(self):
while True:
file_name = input("Please enter a file name or enter 'done' to exit the program: ")
if file_name == "done":
print("Bye.")
break
try:
with open(file_name, 'r') as file:
file.read()
print("File is now open.")
I tried so many things, still getting the same problem. I am not sure what to do.
答案1
得分: 0
首先,当使用上下文管理器(with语句)时,不需要使用try except块,因为它们内部已经定义了异常处理程序。
您的程序运行正确,它正在将文件读入缓冲区,但您没有说明您想要查看其中的内容。例如,将file.read()放置在print的参数中,您将在控制台中看到一些输出。
英文:
First of all you don't need to use try except block when using context managers (with statement) as they have exception_handler defined inside them.
Your program run correctly it is reading file to the buffer but you didn't say anywhere you want to see what is inside. For example put file.read() as print argument and you will see some output in console
答案2
得分: -1
首先,你需要在 try
后面加上 except
或 finally
。然后,在完成操作后最好将文件关闭,如下所示。另外,如果你想在控制台输出文件的内容,只需像下面这样打印它。以下代码对我而言成功运行:
while True:
file_name = input("请输入文件名或输入 'done' 退出程序:")
if file_name == "done":
print("再见。")
break
try:
with open(file_name, 'r') as file:
print("文件已打开。")
print(file.read())
file.close()
except:
print("发生异常")
希望这有所帮助。
英文:
first of all, you would need an except
or finally
after try
.
Then, it is also better and cleaner to close the file after you are done with, as implemented below. Also, if you want to output the contents of the file in the console, you need to just print it, as done below. The following code below worked successfully for me:
<br>
Like this:
while True:
file_name = input("Please enter a file name or enter 'done' to exit the program: ")
if file_name == "done":
print("Bye.")
break
try:
with open(file_name, 'r') as file:
print("File is now open.")
print(file.read())
file.close()
except:
print("An exception occurred")
Hope this helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论