ITeye博客

Python 中读写文件的安全写法 (异常处理)

eric_wyf · 2011-09-21 15:50 · python · 互联网 · Markdown

f = open( "hello.txt")
try :
    for line in f:
        print line
finally :
    f.close()

 

 

对文件的打开和读写部分要分开处理异常:若文件未成功打开,则只需进行普通处理,不必进行close()操作,不要把open语句写到try语句块中

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。