Python3读取UTF-8文件及统计文件行数的方法
作者:皮蛋 时间:2022-06-03 15:02:45
本文实例讲述了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程序设计有所帮助。
标签:Python,读取,文件,行数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
常用python数据类型转换函数总结
2023-07-27 23:07:16
pycharm开发一个简单界面和通用mvc模板(操作方法图解)
2022-10-09 06:28:39
![](https://img.aspxhome.com/file/2023/3/90283_0s.png)
Python 动态绑定属性和方法
2021-03-02 21:25:34
Django学习笔记之ORM基础教程
2022-07-25 22:59:07
![](https://img.aspxhome.com/file/2023/2/78722_0s.png)
Python try except异常捕获机制原理解析
2023-04-12 20:00:35
![](https://img.aspxhome.com/file/2023/5/70855_0s.png)
Python3 Tkinkter + SQLite实现登录和注册界面
2023-10-01 14:56:15
![](https://img.aspxhome.com/file/2023/5/62945_0s.jpg)
爬山算法简介和Python实现实例
2023-08-10 04:56:29
浅谈Python数学建模之线性规划
2021-02-11 17:57:35
![](https://img.aspxhome.com/file/2023/5/82885_0s.png)
Frontpage中网页字体的美化研究
2008-03-10 12:13:00
python openvc 裁剪、剪切图片 提取图片的行和列
2022-07-03 15:29:40
![](https://img.aspxhome.com/file/2023/4/77874_0s.jpg)
Python爬虫获取整个站点中的所有外部链接代码示例
2021-03-01 09:52:39
![](https://img.aspxhome.com/file/2023/2/97722_0s.jpg)
解决Python requests 报错方法集锦
2023-05-05 20:21:27
django自带的权限管理Permission用法说明
2023-07-25 04:18:06
![](https://img.aspxhome.com/file/2023/1/61491_0s.jpg)
python神经网络tf.name_scope和tf.variable_scope函数区别
2021-01-24 13:10:48
asp如何阻止别人非法链接你网站的图片?
2010-07-11 21:01:00
php遍历CSV类实例
2023-11-01 23:46:26
卓越网的配送服务让我很不满意
2009-03-19 13:49:00
![](https://img.aspxhome.com/file/UploadPic/20093/19/dingdan-600x456-50s.jpg)
ASP名次排列函数
2008-07-20 13:42:00
python第三方库pygame的使用详解
2023-07-21 13:27:19
![](https://img.aspxhome.com/file/2023/6/97706_0s.jpg)
Python性能分析工具py-spy原理用法解析
2021-08-30 14:57:23
![](https://img.aspxhome.com/file/2023/1/89441_0s.png)