Home > Article > Backend Development > Use python script to count the number of lines in a file
Python can count the number of lines in a file, do you believe it? Whether you believe it or not, I do. Let's take a look at how python counts the number of lines in a file. The code is very simple. I also made comments and it is very simple to implement. . .
1
2
3
4
5
6
7
8
9
#_*_coding:utf_8 #引入sys和系统os模块 import sys import os ''' 计算某一个文件的行数 ''' def countFileLines(filename): count = 0 try: handle = open(filename, 'r') #循环文件句柄 for eachline in handle: #累加 count += 1 #异常捕获 except IOError, e: print 'file open error', e return count print countFileLines('/home/pythontab/tmp/a.php')