Skip to content

Instantly share code, notes, and snippets.

@0xjams
Created October 15, 2024 01:16
Show Gist options
  • Save 0xjams/2beec0af3b594e365cbcff878e16e3ce to your computer and use it in GitHub Desktop.
Save 0xjams/2beec0af3b594e365cbcff878e16e3ce to your computer and use it in GitHub Desktop.
Get students with grades ge 40 and below 70
import csv
import sys
import re
def print_csv_info(file_path):
try:
with open(file_path, 'r', encoding='utf-8-sig') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
headers = next(reader)
print("CSV file information:")
print(f"Delimiter: '{dialect.delimiter}'")
print("Column names found:")
for i, header in enumerate(headers):
print(f" {i+1}. {header}")
except Exception as e:
print(f"Error reading CSV file: {str(e)}")
def find_score_column(headers):
pattern = r'Calificación general \[Puntos totales: hasta 100 Puntuación\] \|\d+'
for header in headers:
if re.match(pattern, header):
return header
return None
def filter_students_by_score(file_path, min_score=40, max_score=69):
filtered_students = []
try:
with open(file_path, 'r', encoding='utf-8-sig') as csvfile:
csvreader = csv.DictReader(csvfile)
headers = csvreader.fieldnames
if 'Apellidos' not in headers or 'Nombre' not in headers:
print("Error: 'Apellidos' or 'Nombre' column not found.")
print_csv_info(file_path)
return []
score_column = find_score_column(headers)
if not score_column:
print("Error: Score column not found.")
print_csv_info(file_path)
return []
print(f"Using score column: {score_column}")
for row in csvreader:
score = row[score_column]
score = float(score.replace(',', '.')) # Convert comma to dot for float conversion
if min_score <= score <= max_score:
full_name = f"{row['Apellidos']}, {row['Nombre']}"
filtered_students.append((full_name, score))
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"Error processing CSV file: {str(e)}")
print_csv_info(file_path)
return filtered_students
def main():
if len(sys.argv) != 2:
print("Usage: python script.py <path_to_csv_file>")
sys.exit(1)
file_path = sys.argv[1]
filtered_students = filter_students_by_score(file_path)
if filtered_students:
print("\nStudents with scores between 40 and 69:")
for student, score in filtered_students:
print(f"{student}: {score:.2f}")
else:
print("\nNo students found with scores between 40 and 69.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment