Created
June 26, 2021 06:47
-
-
Save t0yohei/7d753033fb3c3caafdbdbc064fded5f5 to your computer and use it in GitHub Desktop.
unix `nl` command like code with python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example: python nl.py fizz_buzz.py | |
import sys | |
def display_lines_with_number(lines): | |
i = 1 | |
for line in lines: | |
# 改行コードの場合は、行番号を振らずに表示する | |
if line == "\n": | |
print(line, end="") | |
continue | |
print(f" {str(i)} {line}", end="") | |
i += 1 | |
argc = len(sys.argv) | |
if argc == 1: | |
f = sys.stdin | |
elif argc == 2: | |
try: | |
f = open(sys.argv[1], "r") | |
except FileNotFoundError: | |
sys.exit("wc: No such file or directory: " + sys.argv[1]) | |
else: | |
sys.exit("usage: wc [file]") | |
display_lines_with_number(f.readlines()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment