Help in Python files

0

I have this code:

import sys
import time
import fileinput
from os import system
from os.path import isfile

class Student:
  def fill(self):
    self.id = input("ID: ")
    self.name = input("Nombre: ")
    self.age = int(input("Edad: "))
    self.address = input("Dirección: ")

  def edit_mode(self):
    self.id = input("ID: (enter to skip) ") or self.id
    self.name = input("Nombre: (enter to skip) ") or self.name
    self.age = input("Edad: (enter to skip) ") or self.age
    self.address = input("Dirección: (enter to skip) ") or self.address

  def to_csv_line(self):
    return f"{self.id},{self.name},{self.age},{self.address}"

class StudentRepository:
  @classmethod
  def create(self, student):
    with open("students.csv", "a") as file:
      file.write("\n")
      file.write(student.to_csv_line())

  @classmethod
  def edit(self, student):
    with fileinput.FileInput("students.csv", inplace=True, backup=".bak") as file:
      for line in file:
        data = line.split(",")
        if (data[0] == student.id):
          print(student.to_csv_line())
          return None

  @classmethod
  def search(__self, id):
    student = None
    with open("students.csv", "r") as file:
      for line in file:
        data = line.split(",")
        if data[0] == id:
          student = Student()
          student.id = data[0]
          student.name = data[1]
          student.age = int(data[2])
          student.address = data[3]
          return student


# Menú principal
def menu():
  option = input("""
  +==========================================+
  |                                          |
  |          Control de estudiantes          |
  |                                          |
  +==========================================+

  [?] Seleccione opción:

  1. Ingresar un estudiante
  2. Buscar un estudiante
  3. Salir

  > """)

  if option == "1":
    student = Student()
    student.fill()
    StudentRepository.create(student)
    print("""
  [✓] Estudiante creado.
  [↺] Volviendo al menú en 2s
    """)
    time.sleep(1.5)
    system("clear")
    return menu()

  if option == "2":
    id = input("\nIngresa el ID: ")
    student = StudentRepository.search(id)
    if student is not None:
      return search_menu(student)
    else:
      print("""
  [✕] Estudiante no encontrado.
  [↺] Volviendo al menú en 2s
      """)
      time.sleep(1.5)
      system("clear") # limpia la pantalla
      menu()
  if option == "3":
    print("Good Bye")
    sys.exit(0)

# Menú de búsqueda
def search_menu(student):
  option = input(f"""
  [✓] Estudiante encontrado:

  ID: {student.id}
  Nombre: {student.name}
  Edad: {student.age}
  Dirección: {student.address}

  [?] Seleccione opción:

  1. Editar estudiante
  3. Volver

  > """)

  if (option == "1"):
    student.edit_mode()
    StudentRepository.edit(student)
    print("""
  [✓] Estudiante actualizado:
  [↺] Volviendo al menú en 2s
    """)
    time.sleep(2)
    system("clear")
    return menu()
  if option == "3":
    system("clear")
    return menu()

menu() 

and suspiciously it should work fine but it does not save the information that I change but the file goes blank.

    
asked by Luis David Jimenez 18.04.2017 в 00:02
source

1 answer

1

Class method edit of class StudentRepository just as it is written in the file the student edited. To only modify the line of that student and copy the others you have to go through the entire file and for each row call print . The code is only called print if the id matches the student edited by what that line is written and then the cycle is broken by return .

On the other hand there are inconsistencies with the line breaks. The print function adds a new default line break, line break that is already included by the create method and that is not removed by the search method when you create each instance. All this causes that when editing students empty lines are created in the document.

You can follow different strategies, for example one of them would be:

  • Make the literal formatted string of create already include the line break.

  • In search make strip on each line to eliminate line breaks.

  • Delete the automatic line break from print or use sys.stdout instead.

  • With this I believe that you should not create blank lines at any time.

    The code would look like this:

    import sys
    import time
    import fileinput
    from os import system
    from os.path import isfile
    
    class Student:
      def fill(self):
        self.id = input("ID: ")
        self.name = input("Nombre: ")
        self.age = int(input("Edad: "))
        self.address = input("Dirección: ")
    
      def edit_mode(self):
        self.id = input("ID: (enter to skip) ") or self.id
        self.name = input("Nombre: (enter to skip) ") or self.name
        self.age = input("Edad: (enter to skip) ") or self.age
        self.address = input("Dirección: (enter to skip) ") or self.address
    
      def to_csv_line(self):
        return f"{self.id},{self.name},{self.age},{self.address}\n"
    
    class StudentRepository:
      @classmethod
      def create(cls, student):
        with open("students.csv", "a") as file:
          file.write(student.to_csv_line())
    
      @classmethod
      def edit(cls, student):
        with fileinput.FileInput("students.csv", inplace=True, backup=".bak") as file:
          for line in file:
            data = line.split(",")
            if (data[0] == student.id):
              line = student.to_csv_line()
            print(line, end='')
    
      @classmethod
      def search(cls, id):
        student = None
        with open("students.csv", "r") as file:
          for line in file:
            data = line.strip().split(",")
            if data[0] == id:
              student = Student()
              student.id = data[0]
              student.name = data[1]
              student.age = int(data[2])
              student.address = data[3]
              return student
    
    
    # Menú principal
    def menu():
      option = input("""
      +==========================================+
      |                                          |
      |          Control de estudiantes          |
      |                                          |
      +==========================================+
    
      [?] Seleccione opción:
    
      1. Ingresar un estudiante
      2. Buscar un estudiante
      3. Salir
    
      > """)
    
      if option == "1":
        student = Student()
        student.fill()
        StudentRepository.create(student)
        print("""
      [✓] Estudiante creado.
      [↺] Volviendo al menú en 2s
        """)
        time.sleep(1.5)
        system("cls")
        return menu()
    
      if option == "2":
        id = input("\nIngresa el ID: ")
        student = StudentRepository.search(id)
        if student is not None:
          return search_menu(student)
        else:
          print("""
      [✕] Estudiante no encontrado.
      [↺] Volviendo al menú en 2s
          """)
          time.sleep(1.5)
          system("cls") # limpia la pantalla
          menu()
      if option == "3":
        print("Good Bye")
        sys.exit(0)
    
    # Menú de búsqueda
    def search_menu(student):
      option = input(f"""
      [✓] Estudiante encontrado:
    
      ID: {student.id}
      Nombre: {student.name}
      Edad: {student.age}
      Dirección: {student.address}
    
      [?] Seleccione opción:
    
      1. Editar estudiante
      3. Volver
    
      > """)
    
      if (option == "1"):
        student.edit_mode()
        StudentRepository.edit(student)
        print("""
      [✓] Estudiante actualizado:
      [↺] Volviendo al menú en 2s
        """)
        time.sleep(2)
        system("cls")
        return menu()
      if option == "3":
        system("cls")
        return menu()
    
    menu() 
    

    The menu is adapted to Windows when cleaning the console ( system("cls") ), if you use Linux, leave it as you have it ( system("clear") ).

    PEPs recommend using cls instead of self in class methods, unlike instance methods, however it is a recommendation not an error.

        
    answered by 18.04.2017 в 01:56