Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26312832
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Python/Ruby

2010-07-06 21:19:33

在Python中,最常见的方式来读取文件中的行是执行下列操作:
for line in open('myfile','r').readlines():
do_something(line)

When this is done, however, the readlines() function loads the entire file into memory as it runs.当这样做,但是,readlines()函数加载到内存中整个文件,因为它运行!

如果这个文件比较大如达到1G以上的话就会将其全部读入到内存了。程序会挂起来。

目前我查到的可供选择的解决办法:

#BUF_SIZE = 1024
#bigfile = open('tmplog.log','r')
#tmp_lines = bigfile.readlines(BUF_SIZE)
#while tmp_lines:
# for line in tmp_lines:print line
# tmp_lines = bigfile.readlines(BUF_SIZE)


一次读一部分数据!

法2.
for line in fileinput.input(['tmplog.log']):
    print line
利用fileinput模块处理!


阅读(857) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~