替换csv文件中的特定数据 [英] Replacing specific data in a csv file

查看:480
本文介绍了替换csv文件中的特定数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在进行一个测验,作为我和我的朋友之间的竞争,并且了解更多关于我是相对新的编程。我的程序旨在为每个使用测验的用户保留最后3个结果,并用最新的结果替换最旧的结果。我已经达到的目前阶段能够检查用户是否在文件中有他们的名字,如果没有正常写入文件。

I'm currently in the process of producing a quiz as a competition between me and my friends, and to learn a bit more about programming which I am relatively new to. My program is intended to keep the last 3 results for each user that uses the quiz and replaces the oldest result with the newest. The current stage I have reached is being able to check if the user has their name in the file, and if not writes to the file as normal.

    if team == 'Team 1':
        path = 'team1scores.csv'

    elif team == 'Team 2':
        path = 'team2scores.csv'

    elif team == 'Team 3':
        path = 'team3scores.csv'

    else:
        print("--Error Defining File Path--")

with open(path, 'rt') as csvfile:
    ver_read = csv.reader(csvfile, delimiter =",")
    ver_write = csv.writer(csvfile, delimiter =",")
    for row in ver_read:
        if user in row:
            row_data = list(ver_read)
            row_len = len(row_data)
            if row_len >= 3:
            >>> The Problem is here

        else:
            with open(path, 'a+', newline='') as csvfile:
                csvwriter = csv.writer(csvfile, delimiter=',')
                csvwriter.writerows(datacsv)

能够替换结果,说我已经在我的csv文件中有3个输入下面的数据。这些需要保存在两个不同的列中。

The problem I have with the program is being able to replace the result, say I had the data below in my csv file with 3 inputs already. These need to be kept in two different columns. As I plan to have a sorting feature included.

Jake,5
Jake,7
Jake,2
Max,9
Lee,8

上面的代码的基础,但我困惑一旦程序达到替换信息的情况。到目前为止,我已经能够覆盖整个文件,但不能覆盖特定的数据。

I have experimented several times with the basis of the code above but I am confused once the program reaches the situation of replacing the information. So far I have been able to overwrite the entire file but not specific pieces of data.

在后续步骤中,是否需要 ver_write

Will the ver_write be neccessary in the next steps?

编辑:
我现在有一个更新的版本,但仍有同样的问题,这个程序改编自2ps的答案进入我的标准。它仍然需要覆盖,需要打印到两个不同的单元格的名称和分数。基础是我需要的,但它不会工作。

I now have an updated version but still have the same problem, This program is adapted from 2ps's answer to fit into my criteria. It still needs to overwrite and needs to print to two different cells for the name and the score. The basis is there for what I need but it won't work.

from collections import OrderedDict
user_data = OrderedDict()
data_to_write = []
with open(path, 'r+') as csvfile:
    ver_read = csv.reader(csvfile, delimiter =";")
    for x, row in enumerate(ver_read):
        if user == row[0]:
            user_data[x] = row
        else:
            data_to_write.append(row)
    if len(user_data) > 2:
        keys = user_data.keys()[-2:]
        for x in keys:
            data_to_write.append(user_data[x])
            data_to_write.append(datacsv)
            with open(path, 'w') as csvfile:
                ver_write = csv.writer(csvfile, delimiter=",")
                ver_write.writerows(data_to_write)
    else:
        with open(path, 'a+', newline='') as csvfile:
            csvwriter = csv.writer(csvfile, delimiter=',')
            csvwriter.writerows(datacsv) 

我从根本上做错了吗?

推荐答案

from collections import OrderedDict
user_data = OrderedDict() # dict to hold all matching rows for the user, keyed off of line number
data_to_write = []
with open(path, 'r') as csvfile:  # read-write mode for file
    ver_read = csv.reader(csvfile, delimiter =",")
    for x, row in enumerate(ver_read):
        if user == row[0]:
            user_data[x] = row
        else:
            data_to_write.append(row)   # store it for afterwards
    if len(user_data) >= 3:
        keys = user_data.keys()[-2:] # Grab the last two scores in the file
        for x in keys:
            data_to_write.append(user_data[x])
        # Write the contents of the new score here:
        data_to_write.append(. . . . .)
with open(path, 'w') as csvfile:
    # finally write the changes to file
    ver_write = csv.writer(csvfile, delimiter=",")
    ver_write.writerows(data_to_write)

这篇关于替换csv文件中的特定数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆