Python文件读取的3种方法及路径转义

yipeiwu_com6年前Python基础

1.文件的读取和显示

方法1:

复制代码 代码如下:

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

方法2:
 
复制代码 代码如下:

 try:
     t=open(r'G:\2.txt')
     print t.read()
 finally:
     if t:
        t.close()

方法3:
复制代码 代码如下:

 with open(r'g:\2.txt') as g:
     for line in g:
         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测试一下是怎样转义的:
复制代码 代码如下:

 Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
 Type "copyright", "credits" or "license()" for more information.
 >>> f='g:\a.txt' 
 >>> print f
 g:.txt  #这里被转义成一个特殊符号了。
 >>> f1='g:\\a.txt'
 >>> print f1
 g:\a.txt  #没被转义
 >>> r'g:\a.txt'
 'g:\\a.txt'  #没被转义
 >>> 'g:\a.txt'
 'g:\x07.txt'  #这里将a转义
 >>> 'g:\\a.txt'
 'g:\\a.txt'
 >>>
 

相关文章

Python 深入理解yield

只是粗略的知道yield可以用来为一个函数返回值塞数据,比如下面的例子: ˂!-- Code highlighting produced by Actipro CodeHighligh...

python进程管理工具supervisor使用实例

python进程管理工具supervisor使用实例

平时我们写个脚本,要放到后台执行去,我们怎么做呢? 复制代码 代码如下: nohup python example.py 2>&1 /dev/null & 用tumx或者scre...

python遍历文件夹找出文件夹后缀为py的文件方法

大学毕业, 想看看大学写了多少行代码。 #coding=utf-8 import os class Solution: def __init__(self): self.dir...

详解Python3 pickle模块用法

pickle(python3.x)和cPickle(python2.x的模块)相当于java的序列化和反序列化操作。 常采用下面的方式使用: import pickle pickle...

Python基础入门之seed()方法的使用

 seed() 设置生成随机数用的整数起始值。调用任何其他random模块函数之前调用这个函数。 语法 以下是seed()方法的语法: seed ( [x] ) 注意...