1
resposta

Minha RESPOSTA: 09 Desafio: escrevendo e lendo arquivos csv

import csv
from pathlib import Path

file_path = "students.csv"


def create_file(file_path):
    try:
        with open(file_path, "w", newline="", encoding="utf-8") as file:
            writer = csv.writer(file)
            writer.writerow(["student", "grade"])
    except PermissionError:
        print("You don't have permission to access this file.")


def check_path_exists(file_path):
    try:
        return Path(file_path).exists()
    except PermissionError:
        print("You don't have permission to access this file.")


students = []


def register_student():

    while True:
        exit = False
        name = input("Student: ").strip().title()
        grade = float(input("grade: "))
        students.append([name, grade])
        while True:
            choice = (
                input("Type Y to continue or N to exit the program: ").strip().upper()
            )
            if choice in "YN":
                break
            print("Invalid choice.")

        if choice == "N":
            exit = True
        if exit:
            break

    return students


def verify_file(file_path):
    try:
        path_exists = check_path_exists(file_path)
        # print(path_exists)
        if not path_exists:
            create_file(file_path)
    except PermissionError:
        print("You don't have permission to access this file.")


def write_file():
    try:
        verify_file(file_path)

        students_list = register_student()

        with open("students.csv", "a", newline="", encoding="utf-8") as file:
            writer = csv.writer(file)
            writer.writerows(students_list)
            print("Students registered successfully.")

    except FileNotFoundError:
        print("File was not found.")


write_file()
  • Ler o arquivo:
import csv


file_path = "students.csv"


def read_csv_file(file_path):
    try:
        with open(file_path, "r", newline="", encoding="utf-8") as read_file:
            data = csv.reader(read_file)
            for row in data:
                print(row)

    except FileNotFoundError:
        print("File was not found.")
    except PermissionError:
        print("You don't have permission to access this file.")


def read_csv_grades_equal_above_7(file_path):
    try:
        with open(file_path, "r", newline="", encoding="utf-8") as read_file:
            data = csv.reader(read_file)
            # skip header
            next(data)
            print("\nStudents with grades equal or above 7:\n")
            for row in data:
                try:
                    grade = float(row[1])
                    if grade >= 7:
                        print(f"Student: {row[0]} | grade: {row[1]}")
                except (ValueError, IndexError):
                    continue

    except FileNotFoundError:
        print("File was not found.")
    except PermissionError:
        print("You don't have permission to access this file.")


read_csv_file(file_path)

read_csv_grades_equal_above_7(file_path)
1 resposta

Olá, Thaís! Como vai?

Parabéns pela resolução da atividade!

Observei que você explorou o uso de manipulação de arquivos para registrar dados, utilizou muito bem listas para armazenar os estudantes e ainda compreendeu a importância do tratamento de exceções para garantir robustez no programa.

Permaneça postando as suas soluções, com certeza isso ajudará outros estudantes e tem grande relevância para o fórum.

Ícone de sugestão Para saber mais:

Sugestão de conteúdo para você mergulhar ainda mais sobre o tema:

Fico à disposição! E se precisar, conte sempre com o apoio do fórum.

Abraço e bons estudos!

AluraConte com o apoio da comunidade Alura na sua jornada. Abraços e bons estudos!