midea2 发表于 2015-12-1 10:55:41

python文件_读取

  1.文件的读取和显示
  方法1:



1 f=open(r'G:\2.txt')
2 print f.read()
3 f.close()
  方法2:
  



1 try:
2   t=open(r'G:\2.txt')
3   print t.read()
4 finally:
5   if t:
6      t.close()
  
  方法3:



1 with open(r'g:\2.txt') as g:
2   for line in g:
3         print line
  python虽然每次打开文件都要关闭,但是可能会由于异常导致未关闭,因此我们最好是手动关闭,方法二通过异常处理来进行,方法三通过with来自动调用close方法,最简便。
  这里open的地址需要注意,如果我们写成open('g:\2.txt','r')运行时会报错:IOError: 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) 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 >>> r'g:\a.txt'
10 'g:\\a.txt'#没被转义
11 >>> 'g:\a.txt'
12 'g:\x07.txt'#这里将a转义
13 >>> 'g:\\a.txt'
14 'g:\\a.txt'
15 >>>
  
  
  
  
页: [1]
查看完整版本: python文件_读取