multiple values per row to file - python

时间:2016-04-25 09:32:53

标签: python csv file-io python-3.5

I'm trying to store scores per user to a file in python and I'm not being able to.

I have two lists, names[] & points[]. Everytime the program runs it appends user and score, but when it's run again, the score in the file gets overwritten rather than added to that user.

def quiz():

names=[]
points=[]
name=input("What is your name?")
for x in range (0,1)
    pnt=0  
    num1=3
    num2=4
    print("Whats", num1, '+', num2)
    answer = num1+num2
 userAns=int(input())
 if userAns==answer:
    print("Excellent")
    pnt = pnt+1
 else:
    print("wrong") 
    print("Well done", name, "you scored", point, "/10")
    points.append(point)
    names.append(name)
    class_name = class_name + ".csv"   
    c=open(class_name , 'a+') ##This part forward it prints to another row rather then appending score in the same row
    mw = csv.writer(c)
    rows = zip(names,points)
    mw.writerows(rows)
    c.close()

I need to print the user and then multiple scores alongside it, any help would be appreciated

1 个答案:

答案 0 :(得分:0)

嗯,您的代码无法运行,并且它看起来不像它应该做的甚至是关于将值附加到同一行的部分。我很困惑你要做什么的实际要求,但是要将值附加到同一行(假设每个用户都有自己的文件):

c=open(class_name , 'a+') 

可以更改为

c=open(class_name , 'rb+')  # csv are considered as binary files
c.seek(-2,2) # go to \r\n
mv.writerows(   #... write now

或者,如果所有用户和分数都在同一个文件中(根据您的描述,它似乎是您想要的),您只需替换当前文件的内容,因此只需正常写入并替换现有内容