Python如何将文件中的每一行声明为变量

时间:2017-08-20 08:15:12

标签: python

我正在尝试分隔每行文件并使用内容创建一个新文件。

这是我的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

这是我的代码尝试但是因为我不知道接下来该做什么而被卡住了。

    with open(home + "\\Desktop\\PADS Assignment\\Student's Mark.txt", "w") as c:
    with open(home + "\\Desktop\\PADS Assignment\\data.txt", "r") as d:
        for line in d:
            module, stdId , atdName , totalMark , mark = line.strip().split()

我希望我的学生的Mark.txt内容为(数字的顺序必须与输出中的顺序相同)

210CT 201707001 Michael_Tan  70.0 17.5 20.0 35.0
210CT 201707002 Jasmine_Tang 80.0 20.5 30.0 38.6

可以这样做吗?

注意:如果内容是正确的,请尽快更改代码

1 个答案:

答案 0 :(得分:1)

我的解决方案首先将所有记录保存到有序字典中,当它处理整个文件时它将保存它。现在我用stdId作为词典的关键词(我想它在所有学生中都是独一无二的)。

from collections import OrderedDict
# Use OrderedDict so the order of inserted students is preserved
records = OrderedDict()
with open("in.txt", "r") as r:
    for 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 the dictionary
            # First replace old totalMark 
            records[stdId]["totalMark"] = totalMark 
            # Add to list current mark
            records[stdId]["marks"].append(mark)

with open("out.txt", "w") as w:
    # Iterate through records and save it
    for record in records.values():
        w.write(" ".join(record["keep"]) +
                " " + record["totalMark"] +
                " " + " ".join(record["marks"]) +
                "\n")

注意:在Python 3.6中测试

相关问题