在 for 循环中替换文本文件中的一行 {python}

问题描述 投票:0回答:1

尝试用新的更新信息替换文本文件中的一行时遇到问题。 目的是记录特定学生在给定课程或模块中的出勤情况。已经为每门课程创建了一个文本文件,其中已经记录了学生。该脚本接受用户的输入并更新文本文件。

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()

文本文件看起来像这样

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

我一直在网上寻找多种方法来完成这项工作,但我尝试的都没有用,我已经尝试过替换功能,但它没有用,

我是 python 的新手,所以任何建议都将不胜感激

编辑: 现在,什么都不应该写入文件,打印(og_line)就在那里,因为我正在检查我是否正确地将列表转换回字符串。

输入看起来像

模块记录系统 - 考勤 - 选择模块

软_6017

软_6018

1

学生 #1:迈克尔·马丁

礼物

缺席

1

1代表在场,

文本文件中关于 micheal martin 的特定行应该从 迈克尔·马丁:0:0 到 迈克尔·马丁:1:0

对于钙化,如果也选择不存在,同样的事情应该发生,只是调整以便第二个 0 会改变而不是第一个

python updating read-write
1个回答
0
投票

您可以先加载记录,更新它们,最后将它们全部写回:

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()
© www.soinside.com 2019 - 2024. All rights reserved.