我如何在python3中读取,写入和更新csv值

时间:2019-10-03 12:30:38

标签: python-3.x

假设file.csv只有一个值(1200)。在游戏中,要求值(1200)在获得新的最高分后立即改变。并返回也无法正常工作。我是编程的新手,所以请认真检查。

def loadScore(self):
    with open('persons.csv', "r") as csv_file:
        reader = csv.reader(csv_file)
        return (reader)

def saveScore(self):
    if self.score > self.highScore:
        with open('persons.csv', "w") as csv_file:
            csvwriter = csv.writer(csv_file)
            csvwriter.write(self.score)
            # data.write(str(self.score))

错误:: TypeError:'int'和'_csv.reader'实例之间不支持'>'

1 个答案:

答案 0 :(得分:0)

loadScore函数中,您仅返回读取的对象,而不是值。将函数更改为仅返回第一行可能会解决您的问题:

def loadScore(self):
    with open('persons.csv', "r") as csv_file:
        reader = csv.reader(csv_file)
        return next(reader)

next()在此处返回文件中的第一个值。如果文件中确实有多个值,则应使用:

def loadScore(self):
    with open('persons.csv', "r") as csv_file:
        reader = csv.reader(csv_file)
        for row in reader:
            # Do something with each row
            ...