在Python中修改和重写.csv文件

时间:2015-05-07 18:24:20

标签: python csv

我正在尝试从.csv文件中读取信息,更改特定行,然后重写该文件。我的代码如下:

import csv

forename=input("Forename:")
surname=input("Surname:")
percentage=("Percentage number:")

file=open("file1.csv", "r")
read=csv.reader(file)

sort=sorted(read, key=operator.itemgetter(0))

data = [(forename, surname, percentage, "0", "0")]


for line in sort:
    if forename == line[0] and surname == line[1]:
        condition = True
        if line[3] == "0":
            line[3] = score
        elif line [4] == "0":
            line[4] = score
        else:
            line[4] = line[3]
            line[3] = line[2]
            line[2] = score


if condition == False:
    sort.append(data)

file.close()


file=open("file1.csv", "w")
writer=csv.writer(file)

writer.writerows(sort)

file.close()

但是,当我尝试写入文件时,所有数据都进入第一列,并采用列表格式([“forename”,“surname”,“percentage”])。

即使已经有一个具有相同姓氏和姓氏的记录(而不是更改记录,然后重写文件),也会发生这种情况,这表明检查不起作用。

file.csv具有以下内容(用于存储最后三个百分比):

Cara,Day,80,30,40
Eliza,Fyles,60,37,90
Madeliene,Naylor,30,60,60
George,Hughes,34,0,0
Alice,Berger, 23,38,0
Isaac,James,50,60,85
Kyle,Lyons,22,70,35

问题是什么?

3 个答案:

答案 0 :(得分:0)

您希望sort.extend(data)代替append - inspectorG4dget

答案 1 :(得分:0)

首先,您的过滤器无法正常工作,因为您实际上并未修改“sort”对象中的字段。尝试这样的循环:

for line_num in range(len(sort)):
    if forename == sort[line_num][0] and surname == sort[line_num][1]:
        condition = True
        if sort[line_num][3] == "0":
            sort[line_num][3] = percentage
        elif line [4] == "0":
            sort[line_num][4] = percentage
        else:
            sort[line_num][4] = sort[line_num][3]
            sort[line_num][3] = sort[line_num][2]
            sort[line_num][2] = percentage

或者:

new = []
for line in sort:
    if forename == line[0] and surname == line[1]:
        condition = True
        if line[3] == "0":
            line[3] = percentage
        elif line [4] == "0":
            line[4] = percentage
        else:
            line[4] = line[3]
            line[3] = line[2]
            line[2] = percentage
    new.append(line)

if condition == False:
    sort.append(data)
else:
    sort = new

另外,我认为您可能必须将变量“data”设置为列表而不是元组:

data = [forename, surname, percentage, "0", "0"]

答案 2 :(得分:0)

data应该是一个列表,而不是一个里面有元组的列表。

像这样,['Madeliene', 'Naylor', '30', '60', '60']而不是[('John', 'BAtman', 75, '0', '0')]

不知道代码的每一步是做什么可能会导致混乱的情况。我建议您修改data的构建方式,而不是更改向sort添加列表的方式。

In [1597]: sort.append(data)

In [1598]: sort
Out[1598]: 
[['Alice', 'Berger', ' 23', '38', '0'],
 ['Cara', 'Day', '80', '30', '40'],
 ['Eliza', 'Fyles', '60', '37', '90'],
 ['George', 'Hughes', '34', '0', '0'],
 ['Isaac', 'James', '50', '60', '85'],
 ['Kyle', 'Lyons', '22', '70', '35'],
 ['Madeliene', 'Naylor', '30', '60', '60'],
 ['John', 'BAtman', 75, '0', '0']]