2016-03-05 118 views
2

我嘗試了可以​​寫入的每種格式。每當Python到達要追加到Scores.csv的行時,它就會覆蓋該文件。「a」覆蓋文件而不是追加

有沒有錯誤,它只是不會追加。我不確定是否因爲我正在嘗試寫入.csv文件而不是.txt,但是如果是因爲這個原因,則必須有一種解決方法。

下面是錯誤代碼:

#OPEN TEMP_SCORES FILE FOR READING 
with open("temp_Scores.csv", "r") as scorefile: 
    print("\nDEBUG: temp_Scores.csv is open.") 
    reader = csv.DictReader(scorefile) 
    for row in reader: 
     print("\nDEBUG: Reading temp_Scores.csv..") 
     with open("Scores.csv", "w") as scorefile: 
      print("\nDEBUG: Scores.csv is open for writing...") 
      fieldnames = ["Name", "Class", "Score 1", "Score 2", "Score 3"] 
      writer = csv.DictWriter(scorefile, fieldnames=fieldnames) 

      #This line writes the actual "header" or "titles" 
      writer.writeheader() 

      NameExists = False 
      #LOGIC TO DETERMINE WHAT TO WRITE 
      #if new user's name is the same as in the file; 
      if row["Name"] == UserData["Name"]: 
       NameExists = True 
       print("\nDEBUG: Name was found in temp_Scores.csv. Overwriting line..") 

       #if Score 1 doesn't exist; 
       if len(row["Score 1"]) == 0: 
        #makes NEW SCORE 1 the user's score 
        row["Score 1"] = UserData["Score"] 
        #actually write new scores to file 
        writer.writerow({"Name": row["Name"], "Class": UserData["Class"], "Score 1": row["Score 1"], "Score 2": row["Score 2"], "Score 3": row["Score 3"]}) 

       #if Score 2 doesn't exist; 
       elif len(row["Score 2"]) == 0: 
        #makes NEW SCORE 2 the user's score 
        row["Score 2"] = UserData["Score"] 
        #actually write new scores to file 
        writer.writerow({"Name": row["Name"], "Class": UserData["Class"], "Score 1": row["Score 1"], "Score 2": row["Score 2"], "Score 3": row["Score 3"]}) 

       #if Score 3 doesn't exist; 
       elif len(row["Score 3"]) == 0: 
        #makes NEW SCORE 3 the user's score 
        row["Score 3"] = UserData["Score"] 
        #actually write new scores to file 
        writer.writerow({"Name": row["Name"], "Class": UserData["Class"], "Score 1": row["Score 1"], "Score 2": row["Score 2"], "Score 3": row["Score 3"]}) 

       #if all Scores exist already; (update scores) 
       else: 
        #makes NEW SCORE 3 the user's current score 
        newScore3 = UserData["Score"] 
        #makes NEW SCORE 2 the user's OLD SCORE 3 
        newScore2 = row["Score 3"] 
        #makes NEW SCORE 1 the user's OLD SCORE 2 
        newScore1 = row["Score 2"] 
        #gets rid of OLD SCORE 1 

        #actually write new scores to file 
        writer.writerow({"Name": row["Name"], "Class": UserData["Class"], "Score 1": newScore1, "Score 2": newScore2, "Score 3": newScore3}) 

       print("\nDEBUG: Updated new user's line") 

    #if new user's name DOESN'T exist in the file already; 
    if NameExists == False: 
     print("\nDEBUG: Name was not found in temp_Score.csv. Appending new line..") 
     #saves new user's details into a NEW LINE in the ORIGINAL FILE 
     with open("Scores.csv", "a") as scorefile: 
      fieldnames = ["Name", "Class", "Score 1", "Score 2", "Score 3"] 
      writer = csv.DictWriter(scorefile, fieldnames=fieldnames) 

      writer.write({"Name": UserData["Name"], "Class": UserData["Class"], "Score 1": UserData["Score"], "Score 2": "", "Score 3": ""}) 

      print("\nDEBUG: Appended new line onto existing file") 

#temp_Scores.csv is no longer needed, so we're getting rid of it 
os.remove("temp_Scores.csv") 
print("\nDEBUG: Deleted temp_Scores.csv.") 

非常感謝提前任何幫助。

+0

你確定問題不是'打開(「Scores.csv」,「w」)作爲scorefile'位? – user2357112

回答

0

我已經做了幾個小時的思考和重新編碼。

@ jDo下面的答案是正確的,因爲這段代碼重新定義了「scorefile」多行,這導致只有一行被寫入文件。

我已經重寫考慮整個代碼,並與工作解決方案上來:

NameExists = False 
    linesToWrite = {} 
    with open("Scores.csv", "r") as scorefile: 
     reader = csv.DictReader(scorefile) 
     for row in reader: 
      if row["Name"] == UserData["Name"]: 
       NameExists = True 
       if len(row["Score 1"]) == 0: 
        newScore1 = UserData["Score"] 
        newScore2 = "" 
        newScore3 = "" 
        print("\nDEBUG: Writing Score 1: " + newScore1 + " to line " + str(reader.line_num)) 
       elif len(row["Score 2"]) == 0: 
        newScore1 = row["Score 1"] 
        newScore2 = UserData["Score"] 
        newScore3 = "" 
        print("\nDEBUG: Writing Score 1: " + newScore1 + ", Score 2: " + newScore2 + " to line " + str(reader.line_num)) 
       elif len(row["Score 3"]) == 0: 
        newScore1 = row["Score 1"] 
        newScore2 = row["Score 2"] 
        newScore3 = UserData["Score"] 
        print("\nDEBUG: Writing Score 1: " + newScore1 + ", Score 2: " + newScore2 + ", Score 3: " + newScore3 + " to line " + str(reader.line_num)) 
       else: 
        newScore1 = row["Score 2"] 
        newScore2 = row["Score 3"] 
        newScore3 = UserData["Score"] 
        print("\nDEBUG: Writing Score 1: " + newScore1 + ", Score 2: " + newScore2 + ", Score 3: " + newScore3 + " to line " + str(reader.line_num)) 
       linesToWrite[reader.line_num] = {"Name": row["Name"], "Class": UserData["Class"], "Score 1": newScore1, "Score 2": newScore2, "Score 3": newScore3} 
      else: 
       linesToWrite[reader.line_num] = {"Name": row["Name"], "Class": row["Class"], "Score 1": row["Score 1"], "Score 2": row["Score 2"], "Score 3": row["Score 3"]} 
    with open("Scores.csv", "w") as scorefile: 
     fieldnames = ["Name", "Class", "Score 1", "Score 2", "Score 3"] 
     writer = csv.DictWriter(scorefile, fieldnames=fieldnames) 
     writer.writeheader() 
     for key, line in linesToWrite.items(): 
      writer.writerow(line) 
    if not NameExists: 
     linesToWrite = {"Name": UserData["Name"], "Class": UserData["Class"], "Score 1": UserData["Score"], "Score 2": "", "Score 3": ""} 
     with open("Scores.csv", "a") as scorefile: 
      fieldnames = ["Name", "Class", "Score 1", "Score 2", "Score 3"] 
      writer = csv.DictWriter(scorefile, fieldnames=fieldnames) 
      writer.writerow(linesToWrite) 

感謝的人誰分佈在思想或可能的解決方案。

1

您在嵌套循環中多次重新定義「scorefile」。嘗試給每個打開的文件一個新的句柄名稱(「scorefile1」,「scorefile2」,「scorefile3」或其他)以消除歧義。

此外,我沒有看到循環外的「NameExists」的任何定義 - 是否在您粘貼的代碼之前定義?

+0

我沒有寫入多個文件,只有一個。 – Medallyonify

+0

另外,是的,NameExists是在我的代碼片段之前定義的。 – Medallyonify

+1

@Medallyonify你說得對。您只寫入一個文件,但您在同一個句柄下打開多個文件。取消嵌套「打開」可能會修復它,因爲這意味着一次只能打開一個文件(我認爲對單個csv文件的更改(Scores.csv不會產生變化))。無論如何,很高興你解決了它:) – jDo

相關問題