我已經通過互聯網瞭解有關使用.csv模塊的信息;還有一些其他人強調了這個問題,但我還沒有找到具體的解決方案。Python .csv編寫器留空行
目前,排序/寫入/輸出代碼的工作原理是,它將正確的數據輸出到文件,但將空白行留在正確的數據行之間。
只是爲了給下面的代碼添加一些背景知識;我只能輸出每個人的最後3個分數到文件中,我將使用'Name,Class'對作爲數據庫的主鍵,也就是我將識別數據庫的用戶。變量'totalscore','難度','用戶名'和'班級'已經在前面的代碼中定義過了(有很多,並不完全相關,所以我沒有包括它)
savescore = 0
savescore = totalscore * (difficulty + 2) #Multiplies their score out of 10 by difficulty + 2
print("You got " + str(totalscore) + " Out of ten and scored " + str(savescore) + " points")
with open("Scoredatabase.csv","r") as f:
f=csv.reader(f)
NameClassScoreList = []
for line in f:
NameClassScoreList.append(line[0:5]) # Creates a list of all of the entries in the .csv file (List of lists) in the order Name,Class,Score,Score,Score
NameClassList = []
for n in NameClassScoreList:
NameClassList.append([n[0], n[1]]) #Appends a list of pairs of (Name,Class) for all the records in the .csv file
print(NameClassList)
print(NameClassScoreList)
userNameClass=[]
userNameClass=[username,Class] #Creates a variable storing the pair (Name,Class) for the user currently using the program, can later be used to compare with ones in the database
if userNameClass not in NameClassList: #Tests if a user with that username and class already exists (It should append it to the end before sorting)
NameClassScoreList.append([username,Class,str(savescore),'0','0'])
for entry in NameClassScoreList: #Iterates through all of the entries within the NameClassScoreList (Which includes a list of entries in the .csv file)
if entry[0:2] == [username,Class]: #Checks if the username,Class matches
entry[4]=entry[3] #If it does, it moves all of the scores forwards, deleting the the 3rd last and then replaces it with the savescore
entry[3]=entry[2]
entry[2]=str(savescore)
NameClassScoreList = sorted(NameClassScoreList, key=itemgetter(1,0)) #Sorts the NameClassScoreList by Class, then Name alphabetically.
with open("Scoredatabase.csv","w") as f:
writer=csv.writer(f) #should be for n in NameClassScoreList
for entryrow in NameClassScoreList:
writer.writerow((entryrow[0],entryrow[1],entryrow[2],entryrow[3],entryrow[4]))
我想要這樣做,以便在數據輸出到文件時糾正問題,或者在輸出錯誤後修復它(也就是根據文件在文件中的位置)
如果您需要關於該問題的任何澄清只是評論,我會盡快回復,謝謝。