打开一个存储在变量中的Python文件。

huangapple go评论84阅读模式
英文:

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 后面加上 exceptfinally。然后,在完成操作后最好将文件关闭,如下所示。另外,如果你想在控制台输出文件的内容,只需像下面这样打印它。以下代码对我而言成功运行:

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(&quot;Please enter a file name or enter &#39;done&#39; to exit the program: &quot;)

	if file_name == &quot;done&quot;:
    	print(&quot;Bye.&quot;)
	    break

	try:
    	with open(file_name, &#39;r&#39;) as file:
		    print(&quot;File is now open.&quot;)
            print(file.read())
			file.close()
    except:
	    print(&quot;An exception occurred&quot;)

Hope this helps

huangapple
  • 本文由 发表于 2023年7月3日 05:54:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定