#!/usr/bin/env python3 import fcntl import os from sys import argv rows = {} with open("students.textdb.lock", "w") as lock: fcntl.flock(lock, fcntl.LOCK_EX) with open("students.textdb", "rt") as file: for line in file.readlines(): idx, lab, proj, exam = line.strip().split(" ") rows[int(idx)] = (idx, lab, proj, exam) # argv is like # ["set_student_1.py", "512345", "5.0", "3.0", "3.0"] rows[int(argv[1])] = tuple(argv[1:5]) with open("students-tmp.textdb", "wt") as file: for _, (idx, lab, proj, exam) in sorted(dict.items(rows)): print(idx, lab, proj, exam, file=file) file.flush() # make sure buffered data got passed to OS kernel os.fsync(file.fileno()) # make sure data got written to disk os.rename("students-tmp.textdb", "students.textdb")