python计算文件的行数和读取指定行的内容

来源:互联网 发布:115 mac 编辑:程序博客网 时间:2024/06/05 07:41
小文件读取,计算行数

1. count = len(open(filepath,'rU').readlines())

大文件读取,计算行数
2. count = -1
   for count, line in enumerate(open(thefilepath, 'rU')):
       pass
   count += 1

3. count = 0
   thefile = open(thefilepath, 'rb')
   while True:
      buffer = thefile.read(8192*1024)
      if not buffer:
         break
      count += buffer.count('\n')
   thefile.close( )


读取指定行

import linecache

count = linecache.getline(filename,linenum)

0 0
原创粉丝点击