使用Try Except循环写入文件总是导致except块。

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

Writing into a File using a Try Except Loop always results in the except block

问题

def write_string(fname, text):
    try:
        f = open(fname, 'r')
        f.read()
        l = open(fname, 'w')
        return l.write(text)
    except:
        print(f'打开 {fname} 时发生错误')
        return None
英文:

The function should open the file and if an exception occurs the function should display an error message and the function should return None. If an exception does not occur while opening, the code should write into the file text.

def write_string(fname, text):
    try:
        f = open(fname, 'r')
        f.read()
        l = open(fname, 'w')
        return l.write(text)
    except:
        print(f'Error occurred when opening {fname} to read')
        return None

However, it seems to always return an error and never actually write the file. Any advice? I'm still new to Python.

When testing it I get this:
Full printing (excluding input prompts/lines and empty lines) should look something like:

"""
The following (excluding input prompts/lines and empty lines) was printed:
"""
Error occurred when opening basic_io.write_string_0.txt to read
Error occurred when opening basic_io.write_string_0.txt to read

答案1

得分: 1

总体来说,捕获所有异常是不好的做法——你应该捕获你知道如何处理的特定异常(例如,FileNotFoundError 是你在尝试打开文件时可能遇到的特定异常),让其他异常抛出。这样做会使得你的程序在遇到意外异常时更容易调试,因为Python会自动停止程序并打印一个错误消息,告诉你确切是什么异常被抛出以及在哪里,而不是让你陷入一个收到错误消息但不知道是什么原因的情况。

如果你要广泛捕获异常并打印错误消息,你应该强烈考虑打印异常本身包含的错误消息:

def write_string(fname, text):
    try:
        f = open(fname, 'r')
        f.read()
        l = open(fname, 'w')
        return l.write(text)
    except Exception as e:
        print(f'Error occurred when opening {fname} to read: {e}')
        return None

这可能对你有所帮助。

请注意,except 将捕获try块中发生的任何错误,而不仅仅是open(fname, 'r')的调用!因此,你打印的错误信息是误导性的——它可能不一定是因为你打开文件进行读取而发生的。例如,如果我用只读文件运行上面的函数版本,我会得到:

>>> write_string("foo.txt", "asdfasdf")
Error occurred when opening foo.txt to read: [Errno 13] Permission denied: 'foo.txt'

如果我只是移除try/except,错误信息会更具信息性:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    write_string("foo.txt", "asdfasdf")
  File "test.py", line 4, in write_string
    l = open(fname, 'w')
PermissionError: [Errno 13] Permission denied: 'foo.txt'

因为现在我能看到我得到了PermissionError,它发生在open(fname, 'w')调用时,也就是说,我尝试打开文件进行写入,而不是读取。

英文:

In general it's bad practice to catch all exceptions -- you should catch the specific exceptions that you know how to handle (for example, FileNotFoundError is a specific exception you might encounter when trying to open a file), and let others raise. That will make your program easier to debug when you encounter unexpected exceptions, because Python will automatically halt the program and print an error message that tells you exactly what exception was raised and where, instead of putting you in the situation where you're getting an error message but have no idea what's causing it.

If you are going to broadly catch exceptions and print an error message, you should strongly consider printing the error message that's contained in the exception itself:

def write_string(fname, text):
    try:
        f = open(fname, &#39;r&#39;)
        f.read()
        l = open(fname, &#39;w&#39;)
        return l.write(text)
    except Exception as e:
        print(f&#39;Error occurred when opening {fname} to read: {e}&#39;)
        return None

This will probably give you something to go on.

Note that the except will catch any error that happens in the try block, not just the open(fname, &#39;r&#39;) call! So the error you're printing is misleading -- it might not necessarily be something that's happening because you opened the file to read. For example, if I run the above version of the function with a read-only file, I get:

&gt;&gt;&gt; write_string(&quot;foo.txt&quot;, &quot;asdfasdf&quot;)
Error occurred when opening foo.txt to read: [Errno 13] Permission denied: &#39;foo.txt&#39;

If I simply remove the try/except the error is more informative:

Traceback (most recent call last):
  File &quot;test.py&quot;, line 7, in &lt;module&gt;
    write_string(&quot;foo.txt&quot;, &quot;asdfasdf&quot;)
  File &quot;test.py&quot;, line 4, in write_string
    l = open(fname, &#39;w&#39;)
PermissionError: [Errno 13] Permission denied: &#39;foo.txt&#39;

because now I can see that I'm getting a PermissionError and that it happened on the open(fname, &#39;w&#39;) call, i.e. my attempt to open the file for write, not read.

答案2

得分: 1

以下是要翻译的内容:

你没有向期望接受单个参数的write函数传递任何参数。

def write_string(fname, text):
    try:
        f = open(fname, 'r')
        f.read()
        l = open(fname, 'w')
        return l.write(text)
    except:
        print(f'Error occurred when opening {fname} to read')
        return None

应该可以工作。

此外,在你的情况下,我建议使用:-

try:
    # 做一些操作
except Exception as e:
    print(e)

以打印错误消息。

但通常情况下,正如@michael-butscher指出的那样,最好“捕获特定的预期异常”。

英文:

You are not passing any argument to the write function which expects a single argument.

def write_string(fname, text):
    try:
        f = open(fname, &#39;r&#39;)
        f.read()
        l = open(fname, &#39;w&#39;)
        return l.write(text)
    except:
        print(f&#39;Error occurred when opening {fname} to read&#39;)
        return None

should work.

Also, IN YOUR CASE, I would recommend using:-

try:
    # Do something
except Exception as e:
    print(e)

to print the error message.

But generally, as @michael-butscher pointed out, it is better to "catch specific expected expections".

huangapple
  • 本文由 发表于 2023年4月20日 09:28:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059910.html
匿名

发表评论

匿名网友

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

确定