方法一 Python 读取文件
针对小文件可行,大文件效率和性能都很差。以下是几种写法
def
get_count
(
file_abs_name
)
:
"""
:param: file_abs_name 文件名含绝对路径
"""
with
open
(
file_abs_name
,
'r'
)
as
f
:
cnt
=
len
(
f
.
readlines
)
f
.
flush
(
)
return
cnt
def
get_count
(
file_abs_name
)
:
"""
:param: file_abs_name 文件名含绝对路径
"""
with
open
(
file_abs_name
,
'r'
)
as
f
:
cnt
=
0
for
line
in
f
:
cnt
+=
1
f
.
flush
(
)
return
cnt
def
get_count
(
file_abs_name
)
:
"""
论坛很多这种写法,但是大部分都写错了
"""
cnt
=
0
with
open
(
file_abs_name
,
'r'
)
as
f
:
for
index
,
line
in
enumerate
(
f
)
:
pass
f
.
flush
(
)
cnt
=
index
+
1
return
cnt
方法二 Linux 读取文件行数
采用Linux命令的方式,读取效率比较高
import
os
def
get_count
(
file_abs_name
)
:
"""
"""
cmd
=
'wc -l '
+
file_abs_name
return
int
(
os
.
system
(
cmd
)
)
方法三 linecache库 Python第三方库
程序员的正常思路 是在github搜索相关资源
linecache2
https://github.com/testing-cabal/linecache2
该库提供了获取总行数, 以及制定某行内容等的方法
linecache_light
https://github.com/Yelrose/linecache_light
功能同上,内存开销更小