Python How to declare each line in file as a variable -
i trying seperate each line of file , create new file content.
this content of data.txt
210ct 201707001 michael_tan 0 17.5 210ct 201707001 michael_tan 0 20.0 210ct 201707001 michael_tan 70.0 35.0 210ct 201707002 jasmine_tang 0 20.5 210ct 201707002 jasmine_tang 0 30.0 210ct 201707002 jasmine_tang 80.0 38.5
this code attempt i'm stuck don't know next.
open(home + "\\desktop\\pads assignment\\student's mark.txt", "w") c: open(home + "\\desktop\\pads assignment\\data.txt", "r") d: line in d: module, stdid , atdname , totalmark , mark = line.strip().split()
i want student's mark.txt content (the order of number must in output)
210ct 201707001 michael_tan 70.0 17.5 20.0 35.0 210ct 201707002 jasmine_tang 80.0 20.5 30.0 38.6
is possible this?
note: please feel free change code want long content correct
my solution first save records ordered dictionary when process whole file save it. right used key dictionary stdid
(i suppose unique among students).
from collections import ordereddict # use ordereddict order of inserted students preserved records = ordereddict() open("in.txt", "r") r: line in r: # skip empty lines if line == "\n": continue module, stdid, atdname, totalmark, mark = line.strip().split() if stdid not in records: # create new record per student records[stdid] = {"keep": (module, stdid, atdname), "totalmarks": totalmark, "marks": [mark]} else: # update student record of existing students in dictionary # first replace old totalmark records[stdid]["totalmark"] = totalmark # add list current mark records[stdid]["marks"].append(mark) open("out.txt", "w") w: # iterate through records , save record in records.values(): w.write(" ".join(record["keep"]) + " " + record["totalmark"] + " " + " ".join(record["marks"]) + "\n")
note: tested in python 3.6
Comments
Post a Comment