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

python-linecache模块读取文件用法

时间:2015-01-28 19:56:06      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:python-linecache模块读取文件用法

python-linecache模块读取文件用法详解


linecache模块允许从任何文件里得到任何的行,并且使用缓存进行优化,常见的情况是从单个文件读取多行。


1、linecache.getlines(filename)

 从名为filename的文件中得到全部内容,输出为列表格式,以文件每行为列表中的一个元素,并以linenum-1为元素在列表中的位置存储


2、linecache.getline(filename,lineno)

 从名为filename的文件中得到第lineno行。这个函数从不会抛出一个异常–产生错误时它将返回”(换行符将包含在找到的行里)。

如果文件没有找到,这个函数将会在sys.path搜索。


3、linecache.clearcache()

清除缓存。如果你不再需要先前从getline()中得到的行


4、linecache.checkcache(filename)

 检查缓存的有效性。如果在缓存中的文件在硬盘上发生了变化,并且你需要更新版本,使用这个函数。如果省略filename,将检查缓存里的所有条目。


5、linecache.updatecache(filename)

 更新文件名为filename的缓存。如果filename文件更新了,使用这个函数可以更新linecache.getlines(filename)返回的列表。


用法举例:

# cat a.txt

1a

2b

3c

4d

5e

6f

7g


(1)、获取a.txt文件的内容

>>> a=linecache.getlines(‘a.txt‘)

>>> a

[‘1a\n‘, ‘2b\n‘, ‘3c\n‘, ‘4d\n‘, ‘5e\n‘, ‘6f\n‘, ‘7g\n‘]


(2)、获取a.txt文件中第1-4行的内容

>>> a=linecache.getlines(‘a.txt‘)[0:4]

>>> a

[‘1a\n‘, ‘2b\n‘, ‘3c\n‘, ‘4d\n‘]


(3)、获取a.txt文件中第4行的内容

>>> a=linecache.getline(‘a.txt‘,4)

>>> a

‘4d\n‘


注意:使用linecache.getlines(‘a.txt‘)打开文件的内容之后,如果a.txt文件发生了改变,如你再次用linecache.getlines获取的内容,不是文件的最新内容,还是之前的内容,此时有两种方法:

1、使用linecache.checkcache(filename)来更新文件在硬盘上的缓存,然后在执行linecache.getlines(‘a.txt‘)就可以获取到a.txt的最新内容;

2、直接使用linecache.updatecache(‘a.txt‘),即可获取最新的a.txt的最新内容


另:读取文件之后你不需要使用文件的缓存时需要在最后清理一下缓存,使linecache.clearcache()清理缓存,释放缓存。


这个模块是使用内存来缓存你的文件内容,所以需要耗费内存,打开文件的大小和打开速度和你的内存大小有关系。


自己测试的450M文件执行时间,还是open()方法快些,大于1G文件,使用linecache.getlines()方法更好,代码如下:

###使用linecache.getlines方法###

$cat read_file.py

#!/usr/bin/env python
#coding:utf8
import os,linecache,time
def get_content(file):
    content=‘‘
    cache_data=linecache.getlines(file)
    for line in range(len(cache_data)):
        content+=cache_data[line]

    return content

def main():
    file=‘/opt/file_operate/ibdata1‘
    content=get_content(file)

    print content

    linecache.clearcache()
if __name__==‘__main__‘:
    starttime=time.clock()  
    main()
    endtime=time.clock()
    print "total time: %s" %(endtime-starttime)

###使用open()方法###

$cat read_file1.py

#!/usr/bin/env python
#coding:utf8
import time
def read_file(file):
    fo=open(file,‘r‘)
    f=open(‘/opt/file_operate/c.txt‘,‘w‘)
    for line in fo.readlines():
        f.write(line)
    fo.close()
    f.close()
if __name__==‘__main__‘:
    starttime=time.clock()
    read_file(‘/opt/file_operate/ibdata1‘)
    endtime=time.clock()
    print "total time: %s" %(endtime-starttime)


备注:借鉴伟哥的blog部分内容

本文出自 “蜗牛的家” 博客,请务必保留此出处http://winters.blog.51cto.com/5617866/1609307

python-linecache模块读取文件用法

标签:python-linecache模块读取文件用法

原文地址:http://winters.blog.51cto.com/5617866/1609307

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