博主信息
博文 41
粉丝 0
评论 1
访问量 48500
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
Python高效编程技巧实战(7)
yeyiluLAMP
原创
991人浏览过

snipaste20171001_183727.png


通用的方法:

f = open('/var/log/dpkg.log')
lines = f.readlines()
lines[100:300]

使用 readlines 会一致性地将文件导入内存当中,当文件非常大的时候,如某些日志文件,大小可能在几个G的,这样一致性地读入文件的操作方式是不可取的,可能导致内存不足

将文件的指针返回到文件的头部(初始位置)

f.seek(0)
from itertools import islice
for line in islice(f,100,300):
    print(line)
In [89]: islice?
Type:            type
String form:     Init definition: islice(self, *args, **kwargs)
Docstring:
islice(iterable, stop) --> islice object
islice(iterable, start, stop[, step]) --> islice object
Return an iterator whose next() method returns selected values from an
iterable.  If start is specified, will skip all preceding elements;
otherwise, start defaults to zero.  Step defaults to one.  If
specified as another value, step determines how many values are 
skipped between successive calls.  Works like a slice() on a list
but returns an iterator.

前500行

In [90]: islice(f,500)
Out[90]: <itertools.islice at 0xb5c85edc>



100到末行

In [91]: islice(f,100,None)
Out[91]: <itertools.islice at 0xb5c85bbc>

对于负引索是不支持的

In [92]: islice(f,100,-100)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last) in ()
----> 1 islice(f,100,-100)
ValueError: Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.

islice会消耗内部的生成器

In [99]: l = list(range(20))
In [100]: l
Out[100]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
In [101]: t = iter(l)
In [102]: t
Out[102]: In [103]: for x in islice(t,5,10):
   .....:     print(x)
   .....:     
5
6
7
8
9
In [104]: for x in t:
   .....:     print(x)
   .....:     
10
11
12
13
14
15
16
17
18
19



迭代器对象(Python3.x)

In [109]: iter(l) is l
Out[109]: False
In [110]: t = iter(l)
In [111]: t.__next__()
Out[111]: 0
In [112]: t.__next__()
Out[112]: 1
In [113]: t.__next__()
Out[113]: 2
In [114]: next(t)
Out[114]: 3
In [115]: next(t)
Out[115]: 4
In [116]: next(t)
Out[116]: 5


迭代器对象(Python2.x)

In [109]: iter(l) is l
Out[109]: False
In [110]: t = iter(l)
In [111]: t.next()
Out[111]: 0
In [112]: t.next()
Out[112]: 1
In [113]: t.next()
Out[113]: 2
In [114]: next(t)
Out[114]: 3
In [115]: next(t)
Out[115]: 4
In [116]: next(t)
Out[116]: 5


本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学