48 lines
1.5 KiB
Python
48 lines
1.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Line counter utility - counts lines in a file."""
|
|
|
|
import sys
|
|
|
|
def count_lines(filepath):
|
|
"""Count lines in a file, return -1 if file doesn't exist or is unreadable."""
|
|
try:
|
|
with open(filepath, 'r') as f:
|
|
return sum(1 for _ in f)
|
|
except (FileNotFoundError, PermissionError, IOError):
|
|
return -1
|
|
|
|
def count_comma_separated(filepath):
|
|
"""Count items in a comma-separated file (first row, count commas + 1)."""
|
|
try:
|
|
with open(filepath, 'r') as f:
|
|
first_line = f.readline().strip()
|
|
if not first_line:
|
|
return 0
|
|
return len(first_line.split(','))
|
|
except (FileNotFoundError, PermissionError, IOError):
|
|
return -1
|
|
|
|
if __name__ == '__main__':
|
|
if len(sys.argv) != 3:
|
|
print(f"Usage: {sys.argv[0]} <filepath> <mode>", file=sys.stderr)
|
|
print("Modes: count (lines), csv (fields)", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
filepath = sys.argv[1]
|
|
mode = sys.argv[2]
|
|
|
|
if mode == 'count':
|
|
result = count_lines(filepath)
|
|
if result == -1:
|
|
print(f"ERROR: Cannot read file '{filepath}'", file=sys.stderr)
|
|
sys.exit(2)
|
|
print(result)
|
|
elif mode == 'csv':
|
|
result = count_comma_separated(filepath)
|
|
if result == -1:
|
|
print(f"ERROR: Cannot read file '{filepath}'", file=sys.stderr)
|
|
sys.exit(2)
|
|
print(result)
|
|
else:
|
|
print(f"Unknown mode: {mode}", file=sys.stderr)
|
|
sys.exit(1) |