简体   繁体   English

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

[英]Modifying and rewriting .csv files in Python

I am trying to read information from a .csv file, change a particular row, then rewrite the file. 我正在尝试从.csv文件读取信息,更改特定的行,然后重写该文件。 My code is as follows: 我的代码如下:

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()

However, when I try to write to the file, all of the data goes into the first column, and is in the list format (["forename","surname","percentage"]). 但是,当我尝试写入文件时,所有数据都进入第一列,并且采用列表格式([[forename],“ surname”,“ percentage”]])。

This happens even if there is already a record with the same forename and surname (rather than changing the record, then rewriting the file), suggesting that the check isn't working either. 即使已经有相同名称和姓氏的记录也会发生这种情况(而不是更改记录,然后重写文件),这表明该检查也不起作用。

file.csv has the following content (it is made to store the last three percentages): 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

What is the issue? 有什么问题

您需要sort.extend(data)而不是appendinspectorG4dget

First, your filter is not working because you are not actually modifying the fields in the "sort" object. 首先,您的过滤器不起作用,因为您实际上没有在修改“ sort”对象中的字段。 Try a loop like this: 尝试这样的循环:

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

alternatively: 或者:

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

Also, I think you may have to set your variable "data" as a list instead of a tuple: 另外,我认为您可能必须将变量“数据”设置为列表而不是元组:

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

data should be a list and not a list with a tuple inside. data应该是列表,而不是内部有元组的列表。

Like this, ['Madeliene', 'Naylor', '30', '60', '60'] and not this, [('John', 'BAtman', 75, '0', '0')] . 像这样['Madeliene', 'Naylor', '30', '60', '60']而不是这个[('John', 'BAtman', 75, '0', '0')]

Not knowing what each step of the code is doing will probably lead to messy situations. 不知道代码的每个步骤在做什么,可能会导致混乱的情况。 I'd suggest you fix how data is constructed than change how you add a list to sort . 我建议您固定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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM