Replacing a line in text file while in a for loop {python}

90 Views Asked by At

having trouble trying to replace a line in a text file with new updated info. The aim is to record the attendance of specific students in a given course or module. A text file is already created for each course with students recorded already. The script takes in input from the user and is supposed to update the text file.

def record_attendence():
    print("Module Record System - Attendance - Choose a Module")
    print("-"*50)
    print("SOFT_6017")
    print("SOFT_6018")
    module = int(input())
    if module == 1:
        filename = "SOFT_6017.txt"
        with open(filename) as connection:
            for line in connection.readlines():
                i = 1
                print(f"Student #{i}: {line.split(':')[0]} ")
                print("present")
                print("absent")
                attendence = int(input())
                if attendence == 1:
                    og_line = (line.split(':'))
                    og_line[1] = str(int(og_line[1]) + 1)
                    og_line = ":".join(og_line)
                    print(og_line)


def main():
    record_attendence()

main()

The text file looks like this

Micheal Martin:0:0
Bob Wade:0:0
Sarah Norton:0:0

I've been looking online for numerous ways to get this done but nothing I try works, I've tried the replace function but it didnt work,

I'm new to python so any advice would be appreciated

edit: right now, nothing should be written to the file, the print(og_line) is just there because I was checking if I converted the list back into a string properly.

the input would look something like

Module Record System - Attendance - Choose a Module

SOFT_6017

SOFT_6018

1

Student #1: Micheal Martin

present

absent

1

1 represents being present,

the specific line in the text file about micheal martin should change from Micheal Martin:0:0 to Michael Martin:1:0

for calcification, the same thing should be happening if absent is choosen as well, just adjusted so the second 0 would change instead of the first

1

There are 1 best solutions below

0
Mr. Polywhirl On

You could first load the records, update them, and finally write them all back:

def load_record(option):
  match option:
    case 1:
      return "SOFT_6017.txt"
    case 2:
      return "SOFT_6018.txt"

def record_attendence():
  records = []

  print("Module Record System - Attendance - Choose a Module")
  print("-"*50)
  print("1. SOFT_6017")
  print("2. SOFT_6018")
  module = load_record(int(input()))
  
  # Load
  if module is not None:
    with open(module, 'r') as connection:
      records = [line.strip().split(':') for line in connection.readlines()]
  
  # Loop through all records
  for i, record in enumerate(records):
    print(f"Student #{i + 1}: {record[0]}")
    print("1. Present")
    print("2. Absent")
    choice = int(input())
    
    # Update
    if choice >= 1 and choice <= 2:
      record[choice] = str(int(record[choice]) + 1)
  
  # Overwrite
  with open(module, 'w') as f:
    f.writelines([f"{':'.join(record)}\n" for record in records])


def main():
  record_attendence()

main()