1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#!/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")
|