“a”覆盖文件而不是附加

时间:2016-03-05 18:48:21

标签: file csv python-3.x dictionary

我已经尝试过可以编写的每种格式。每当Python到达要附加到Scores.csv的行时,它都会覆盖该文件。

没有错误,它不会附加。我不确定是不是因为我试图写入.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.")

非常感谢您提前提供任何帮助。

2 个答案:

答案 0 :(得分:1)

您在嵌套循环中多次重新定义“scorefile”。尝试给每个打开的文件一个新的句柄名称(“scorefile1”,“scorefile2”,“scorefile3”或其他),以消除歧义。

另外,我没有在循环外看到“NameExists”的任何定义 - 它是在你粘贴的代码之前定义的吗?

答案 1 :(得分: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)

感谢任何分发思想或可能解决方案的人。