码迷,mamicode.com
首页 > 编程语言 > 详细

python文件_读取

时间:2015-04-13 16:33:48      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

1.文件的读取和显示

方法1:

1 f=open(rG:\2.txt)
2 print f.read()
3 f.close()

方法2:

 

1 try:
2     t=open(rG:\2.txt)
3     print t.read()
4 finally:
5     if t:
6        t.close()

 

方法3:

1 with open(rg:\2.txt) as g:
2     for line in g:
3         print line

python虽然每次打开文件都要关闭,但是可能会由于异常导致未关闭,因此我们最好是手动关闭,方法二通过异常处理来进行,方法三通过with来自动调用close方法,最简便。

这里open的地址需要注意,如果我们写成open(‘g:\2.txt‘,‘r‘)运行时会报错:IOError: [Errno 22] invalid mode (‘r‘) or filename: ‘g:\x02.txt‘。这里是由于路径被转义了,因此可以用‘/‘代替‘\‘:f=open(‘g:/2.txt‘,‘r‘)或者加上r‘path‘:f=open(r‘g:\2.txt‘,‘r‘)就可以了。

这里通过python自带的ide-GUI测试一下是怎样转义的:

 1 Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
 2 Type "copyright", "credits" or "license()" for more information.
 3 >>> f=g:\a.txt  
 4 >>> print f
 5 g:.txt  #这里被转义成一个特殊符号了。
 6 >>> f1=g:\\a.txt
 7 >>> print f1
 8 g:\a.txt  #没被转义
 9 >>> rg:\a.txt
10 g:\\a.txt  #没被转义
11 >>> g:\a.txt
12 g:\x07.txt  #这里将a转义
13 >>> g:\\a.txt
14 g:\\a.txt
15 >>> 

 

 

 

 

python文件_读取

标签:

原文地址:http://www.cnblogs.com/tingfenglin/p/4422240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!