注册 登录
编程论坛 Python论坛

一个小白的问题。没有看懂

x0012 发布于 2017-10-31 22:11, 3483 次点击
程序代码:
file_name = 'hello.txt'
try:
    with open(file_name) as f_object:
        conters = f_object.read()
except ZeroDivisionError:
    msg = "Sorry your filename is " + file_name + ' ' + "no."
    print(msg)

代码是这样的,正在学习python异常处理,运行的时候出错,但是没看明白是哪儿出错了,求各位大佬指教
9 回复
#2
yuccn2017-11-04 09:39
需要看错误信息
#3
Myloop2017-11-10 23:56
Traceback (most recent call last):
  File "/Users/apple/PycharmProjects/Myloop_2/Python_1.py", line 14, in <module>
    with open(file_name) as f_object:
FileNotFoundError: [Errno 2] No such file or directory: 'hello.txt'

Process finished with exit code 1
这个是我在PyCharm上面运行的结果,显示我的电脑上并不存在“Hello.txt”这个文件


[此贴子已经被作者于2017-11-11 00:03编辑过]

#4
Myloop2017-11-10 23:57
回复 2楼 yuccn
错误信息如上,Fileopen错误
#5
Myloop2017-11-11 00:02
#需要在文件名前面添加文件所在路径:
file_name = "/Users/apple/Desktop/Txt/hello.txt"
try:
    with open(file_name) as f_object:
        conters = f_object.read()
except ZeroDivisionError:
    msg = "Sorry your filename is " + file_name + ' ' + "no."
    print(msg)

Process finished with exit code 0
#无错无显示,完美
#6
Ye華2018-01-04 11:11
新人小白路过
#7
li3840222018-01-06 16:12
  这是啥 是啥
#8
极客程序员2018-01-09 10:39
打开文件不会报ZeroDivisionError异常吧,应该是捕获不对。
#9
Yinjs2019-08-23 13:51
没有文件操作方式,
#10
陈精的梅先生2019-09-16 17:34
首先你要知道ZeroDivisionError的报错是为什么,其次,你要知道你要捕获的错位类型是否是这个。ZeroDivisionError是在除数为零时的报错类型,你应该是想要捕获FileNotFoundError
1