2015-09-26 60 views
4

我需要一個解決方案來排序我的文件如下所示:如何文件內容進行排序到列表

Super:1,4,6 
Superboy:2,4,9 

我此刻的文件看起來像這樣:

Super:1 
Super:4 
Super:6 

我需要幫助保持在測驗中獲得每個班級成員的分數跟蹤。學校有三個班級,每個班級需要分開存放數據。

我的代碼如下:

className = className +(".txt")#This adds .txt to the end of the file so the user is able to create a file under the name of their chosen name. 

file = open(className , 'a') #opens the file in 'append' mode so you don't delete all the information 
name = (name) 
file.write(str(name + " : ")) #writes the information to the file 
file.write(str(score)) 
file.write('\n') 
file.close() #safely closes the file to save the information 
+1

請轉降低你的代碼的代碼段這不利於故障排除和提供幫助。 – idjaw

回答

6

您可以使用字典對數據進行分組,特別是collections.OrderedDict保持名稱出現在原始文件的順序:

from collections import OrderedDict 

with open("class.txt") as f: 
    od = OrderedDict() 
    for line in f: 
     # n = name, s = score 
     n,s = line.rstrip().split(":") 
     # if n in dict append score to list 
     # or create key/value pairing and append 
     od.setdefault(n, []).append(s) 

它只是一個將字典鍵和值寫入文件的問題,以便使用csv模塊獲得您想要的輸出,從而爲您提供逗號分隔的輸出。

from collections import OrderedDict 
import csv 
with open("class.txt") as f, open("whatever.txt","w") as out: 
    od = OrderedDict() 
    for line in f: 
     n,s = line.rstrip().split(":") 
     od.setdefault(n, []).append(s) 
    wr = csv.writer(out) 
    wr.writerows([k]+v for k,v in od.items()) 

如果你要更新的原始文件,你可以寫一個tempfile.NamedTemporaryFile並用更新使用shutil.move替換原來的:

from collections import OrderedDict 
import csv 
from tempfile import NamedTemporaryFile 
from shutil import move 

with open("class.txt") as f, NamedTemporaryFile("w",dir=".",delete=False) as out: 
    od = OrderedDict() 
    for line in f: 
     n, s = line.rstrip().split(":") 
     od.setdefault(n, []).append(s) 
    wr = csv.writer(out) 
    wr.writerows([k]+v for k,v in od.items()) 
# replace original file 
move(out.name,"class.txt") 

如果你有一個以上的類只使用一個循環:

classes = ["foocls","barcls","foobarcls"] 

for cls in classes: 
    with open("{}.txt".format(cls)) as f, NamedTemporaryFile("w",dir=".",delete=False) as out: 
     od = OrderedDict() 
     for line in f: 
      n, s = line.rstrip().split(":") 
      od.setdefault(n, []).append(s) 
     wr = csv.writer(out) 
     wr.writerows([k]+v for k,v in od.items()) 
    move(out.name,"{}.txt".format(cls)) 
+0

你能解釋一下我需要編輯我的代碼嗎? – super123

+0

@ super123,你需要完全改變你的代碼,使其類似於我在答案中的內容,你需要根據代碼中的字典將每個用戶的分數分組,然後編寫該密鑰,即名稱和分數列表到新文件或使用shutil方法替換原始文件。你目前有不同的分數,所以他們首先必須分組,每個用戶然後寫 –

3

我會提供一些僞代碼來幫助你。

首先你的數據結構應該是這樣的:

data = {'name': [score1, score2, score3]}

那麼你應該按照邏輯應該是這樣的:

Read the file line-by-line 
    if name is already in dict: 
     append score to list. example: data[name].append(score) 
    if name is not in dict: 
     create new dict entry. example: data[name] = [score] 

Iterate over dictionary and write each line to file 
+1

我有一個粗略的理解,我會試驗。謝謝 – super123