Python Cookbook学习记录 ch2_4/5_2013/10/27
2.4从文件中读取指定的行
从根据给定的行号,从文本中读取一行数据
使用python 标准库中linecache模块
>>> import linecache >>> theline = linecache.getline('thefile.txt',3) >>> print theline Using this simple program as a basis, computer science principles or elements of a specific programming language can be explained to novice programmers.
2.5计算文件的行数
计算文件有多少行
a.将每一行放入一个行列表中,计算列表的长度得到行数
>>> count = len(open('thefile.txt').readlines()) >>> print count 4
b.对于非常大的文件,可以使用循环技术方法
for count, line in enumerate(open('thefile.txt', 'rU')): pass >>> count +=1 >>> print count 4
在同时需要用到index和value值的时候可以用到enumerate,参数为可遍历的变量,如字符串,列表等,返回enumerate类。
>>> s = 'Hello World' >>> e = enumerate(s) >>> for item in e: print item (0, 'H') (1, 'e') (2, 'l') (3, 'l') (4, 'o') (5, ' ') (6, 'W') (7, 'o') (8, 'r') (9, 'l') (10, 'd')
浙公网安备 33010602011771号