我目前正在制作一个测验作为我和我的朋友之间的竞赛,并学习更多关于我相对较新的编程。我的程序旨在为使用测验的每个用户保留最后3个结果,并用最新的结果替换最旧的结果。我已经达到的当前阶段是能够检查用户是否在文件中有他们的名字,如果没有正常写入文件。
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个输入的数据。这些需要保存在两个不同的列中。因为我打算包括排序功能。
Jake,5
Jake,7
Jake,2
Max,9
Lee,8
我已经根据上面的代码进行了多次实验,但是一旦程序达到替换信息的情况,我就很困惑。到目前为止,我已经能够覆盖整个文件,但不能覆盖特定的数据。
接下来的步骤中是否需要 ver_write ?
修改 我现在有一个更新版本,但仍然有同样的问题,这个程序改编自2ps的答案,以符合我的标准。它仍然需要覆盖并需要打印到两个不同的单元格以获取名称和分数。基础是我需要的,但它不会起作用。
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)
我在这里做了一些根本错误的事情吗?
答案 0 :(得分:1)
据我所知,你是cannot change one row in a file。所以你必须重写完整的文件。
我不知道您如何插入新数据,但您可以执行以下操作:
import csv
# Assuming new score
new_score = ['Jake', '3']
# Open the file containing the scores
with open('scores.csv', 'r') as csvfile:
ver_read = csv.reader(csvfile, delimiter=',')
# Make a dict that will contain the scores per person
names = {}
for row in ver_read:
# Grab the name and the score
name,score = list(row)
# If it's not in names yet, put it in and make it a list
if name not in names:
names[name] = []
# Append the score to the name list
names[name].append(score)
# Add the new score
names[new_score[0]].append(new_score[1])
with open('scores.csv', 'w') as csvfile:
# Loop the names in the names dict
for name in names:
# If the person has more than 3 scores, only take the last 3
if len(names[name]) > 3:
names[name] = names[name][-3:]
# For each score, print it
for score in names[name]:
print('{},{}'.format(name, score))
#ver_write.writerow([name, score])
在:
Jake,5
Jake,7
Jake,2
Max,9
Lee,8
新分数:
Jake,3
输出:
Jake,7
Jake,2
Jake,3
Max,9
Lee,8
答案 1 :(得分:0)
你可以尝试这样的事情:
data_to_write = []
with open(path, 'r+') as csvfile: # read-write mode for file
ver_read = csv.reader(csvfile, delimiter =",")
row_data = list(ver_read)
for row in row_data:
if user in row:
if row_data.index(row) >= 3: # if we found the user in a row after 3
row = [] # change the information here to whatever suits you
else:
row = [] # or here depending on your logic
data_to_write.append(row) # store it for afterwards
# finally write the changes to file
ver_write = csv.writer(csvfile, delimiter=",")
ver_write.writerows(data_to_write)
答案 2 :(得分:0)
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)