英文:
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, '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
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, 'r')
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:
>>> write_string("foo.txt", "asdfasdf")
Error occurred when opening foo.txt to read: [Errno 13] Permission denied: 'foo.txt'
If I simply remove the try/except
the error is more informative:
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'
because now I can see that I'm getting a PermissionError
and that it happened on the open(fname, 'w')
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, 'r')
f.read()
l = open(fname, 'w')
return l.write(text)
except:
print(f'Error occurred when opening {fname} to read')
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".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论