0
1

More than 3 years have passed since last update.

Linuxのnlコマンドに相当するコードをPythonで実装してみた

Last updated at Posted at 2021-08-28

Linuxのnlコマンドに相当するコードをPythonで実装してみました。

test.txt
AAA
BBB
CCC
nl.py
import sys
if len(sys.argv) > 1:
    try:
        f = open(sys.argv[1], 'r')
    except FileNotFoundError:
        print('Error: File {0} is not found.'.format(
            sys.argv[1]), file=sys.stderr)
        sys.exit(1)
else:
    f = sys.stdin

lines = f.readlines()
f.close()

i = 1
for line in lines:
    if line == '\n':
        print()
        continue
    print('\t' + str(i) + ' ' + line, end='')
    i += 1

出力結果

$ python nl.py test.txt
    1  AAA
    2  BBB
    3  CCC
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1