Home >Backend Development >Python Tutorial >Python3读取UTF-8文件及统计文件行数的方法

Python3读取UTF-8文件及统计文件行数的方法

WBOY
WBOYOriginal
2016-06-10 15:11:451648browse

本文实例讲述了Python3读取UTF-8文件及统计文件行数的方法。分享给大家供大家参考。具体实现方法如下:

''''' 
Created on Dec 21, 2012 
Python 读取UTF-8文件 
统计文件的行数目 
@author: liury_lab 
''' 
# -*- coding: utf-8 -*- 
import codecs 
# 对较小的文件,最简单的方法是将文件读入一个行列表中,
# 然后计算列表的长度即可 
count = len(codecs.open('d:/FreakOut.cpp', 'rU', 'utf-8').readlines())
print(count) 
# 对较大的文件,可循环计数 
count = -1 
for count, line in enumerate(codecs.open('d:/FreakOut.cpp', 'rU', 'utf-8')):
  pass 
count += 1 
print(count) 
# 对于像windows结束标记有'\n'的,还可以有如下办法: 
count = 0 
the_file = codecs.open('d:/FreakOut.cpp', 'rb', 'utf-8') 
while (True): 
  buffer = the_file.read(8192*1024) 
  if not buffer: 
    break 
  count += buffer.count('\n') 
count += 1 
the_file.close() 
print(count) 

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn