2017-08-20 1 views
-1

私はファイルの各行を区切り、その内容で新しいファイルを作成しようとしています。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 

それがこれを行うことが可能である(数の順序は出力に似なければなりません)になりたいですか?

注:それはそれを保存します全体のファイルを処理する際CONTENTが正確であるしかしあなたがAS LONGするコードを変更すること自由に感じなさい

+0

のPython 3.6でテスト出力の最後に、これらの数字の任意の特定の順序はありますか? – Qeek

+2

変換の背景にある論理は何ですか? –

+0

@Qeekはいそれらの番号の順序は出力にある必要があります –

答えて

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

注:

+0

ありがとうございました!!!出来た!!! –

関連する問題