Discuss / Python / 有bug

有bug

Topic source

LesLieM樂

#1 Created at ... [Delete] [Delete and Lock User]
try:
    f = open('/path/to/file', 'r')
    print(f.read())
finally:
    if f:
        f.close()

如果文件打开不成功,if f 语句会报错"NameError: name 'f' is not defined" StackOverflow上是这么写的

f = None
try:
    f = open('/path/to/file', 'r')
    print(f.read())
finally:
    if f is not None:
        f.close()

http://stackoverflow.com/questions/3770348/how-to-safely-open-close-files-in-python-2-4

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

你说的对,所以要用with语句

那请问老师您这里用了一个 if f 语句原本是什么目的呢?

儒生脱尘

#4 Created at ... [Delete] [Delete and Lock User]

报错是因为文件打开的时候抛出了一个错误吧。需要处理一下错误:

try:
    f=open('H:/1.txt','r')
    print(f.read())
except:
    print('打开文件失败!')
finally:
    if 'f' in dir():
        f.close()

LesLieM樂

#5 Created at ... [Delete] [Delete and Lock User]

竟然得到大神回复了,好激动


  • 1

Reply