---
title: "Python 中读写文件的安全写法 (异常处理) "
author: "eric_wyf"
date: "2011-09-21T15:50:00Z"
tags: []
categories: ["互联网"]
slug: "python"
draft: false
lastmod: "2011-09-21T15:50:00Z"
id: 1177145
url: "https://eric-wyf.iteye.com/blog/1177145"
---

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

 

 

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