-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountCSVLine.py
54 lines (46 loc) · 1.92 KB
/
CountCSVLine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import csv
import sys
import json
def count_csv_lines(file_path, output_path, label, color="blue"):
"""
Counts the number of data lines (excluding header) in a CSV file
and writes the count to a JSON file in Shields.io format with a custom label and optional color.
Parameters:
file_path (str): Path to the input CSV file.
output_path (str): Path to the output JSON file.
label (str): Label for the badge.
color (str, optional): Color for the badge. Defaults to 'blue'.
"""
try:
# Open the CSV file in read mode with UTF-8 encoding
with open(file_path, mode='r', encoding='utf-8') as file:
reader = csv.reader(file)
# Skip the header line
next(reader, None)
# Count the lines in the file
line_count = sum(1 for _ in reader)
# Create a JSON structure compatible with Shields.io
badge_data = {
"schemaVersion": 1,
"label": label,
"message": str(line_count),
"color": color
}
# Write the badge data to the output JSON file
with open(output_path, 'w') as json_file:
json.dump(badge_data, json_file, indent=4)
print(f"Badge JSON written to '{output_path}'.")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
# Ensure the script is run with at least three arguments
if len(sys.argv) < 4 or len(sys.argv) > 5:
print("Usage: python count_csv_lines.py <output_path> <file_path> <label> [color]")
else:
output_file = sys.argv[1]
input_file = sys.argv[2]
badge_label = sys.argv[3]
badge_color = sys.argv[4] if len(sys.argv) == 5 else "blue"
count_csv_lines(input_file, output_file, badge_label, badge_color)