看了很多教程,使用 readlines() 读取感觉效率比较低
这里我使用 Python 调用 wc -l
命令
PS : 这个命令存在一个小的可能的不一致是,如果文件最后一行没有换行符,则这一行不会被统计
import osfile_path = '/Users/user/Documents/happy.md'
# 逐行统计
with open(file_path) as myfile:total_lines = sum(1 for line in myfile)print(total_lines)# 调用命令
script = f'wc -l {file_path}'
out = os.popen(script)
ret = out.readlines()pre = '/Users/user'
num = int(ret[0].split(pre)[0].strip()) # 文件行数,可以 try - exception 试试
print(num)
2024-06-05(三)