1 | import sys
|
2 |
|
3 |
|
4 | def main():
|
5 | """
|
6 | print each input filename and the number of lines in it,
|
7 | and print the sum of the number of lines
|
8 | """
|
9 | filenames = sys.argv[1:]
|
10 | sum_nlines = 0
|
11 |
|
12 | if len(filenames) == 0:
|
13 | sum_nlines = count_file_like(sys.stdin)
|
14 | print('stdin: %d' % sum_nlines)
|
15 | else:
|
16 | for f in filenames:
|
17 | n = count_file(f)
|
18 | print('%s %d' % (f, n))
|
19 | sum_nlines += n
|
20 | print('total: %d' % sum_nlines)
|
21 |
|
22 |
|
23 | def count_file(filename):
|
24 | """count the number of lines in a file"""
|
25 | f = open(filename, 'r')
|
26 | nlines = len(f.readlines())
|
27 | f.close()
|
28 | return(nlines)
|
29 |
|
30 |
|
31 | def count_file_like(file_like):
|
32 | """count the number of lines in a file-like object (eg stdin)"""
|
33 | n = 0
|
34 | for line in file_like:
|
35 | n = n+1
|
36 | return n
|
37 |
|
38 |
|
39 | if __name__ == '__main__':
|
40 | main() |
\ | No newline at end of file |