【问题标题】:Changing the last element of a list also overwrites the second last element更改列表的最后一个元素也会覆盖倒数第二个元素
【发布时间】:2020-12-04 03:03:16
【问题描述】:

我有一个遵循以下结构的 csv 文件:

1 start,end,ID
2 int1,int2,string1
3 int3,int4,string2
4 int5,int6,string3
5 int7,int8,string4

我的目标是创建一个新的 csv,它首先为结束值写入唯一的行,然后将起始值作为结束值。

1 start,end,ID
2 int1,int2,string1
3 ,int1,string1
4 int3,int4,string2
5 ,int3,string2

我通过将输入 csv 写入列表并遍历该列表来尝试此操作。对于每一行,在输出列表中追加两个新行。在分别附加第二行之后,将结束值设置为输入列表的开始值。以下是我使用的代码:

import csv

with open(r"input path") as csv_sbw, open("output path","wb") as csv_new:
    csv_in = csv.reader(csv_sbw)
    csv_out = csv.writer(csv_new)
    fields_out = [[]] #list for the output csv
    fields = list(csv_in) #list for the input csv
    fields_out[0] = fields[0] #headline is taken from the input
    fields[0].append("m_value")
    for row in fields[1:]:
        row.append(1)
        if row[2].isdigit() == False and len(row[2]) == 16 and row[2][0] != 0 and row[0] != '' and row[0] != '0' and row[1] != '0': #invalid rows are skipped
            fields_out.append(row) #first row is appended
            fields_out.append(row) #second row is appended
            fields_out[-1][1] = row[0] #the start value of the last appended row is set as an end value
            fields_out[-1][0] = '' #start field of last appended row is deleted
            fields_out[-1][3] = 0
    csv_out.writerows(fields_out) #output csv is written

我没有按照上述示例生成 csv,而是得到以下结果:

1 start,end,ID,m_value
2 1032,1032,'A',0
3 1032,1032,'A',0
4 613,613,'B',0
5 613,613,'B',0

因此,通过更改fields[-1],代码似乎也覆盖了倒数第二行。据我了解,将一行中的两个值附加到一个列表会创建两个新的列表元素,如果我请求list[-1],则只会返回最后一个附加值。 如何防止代码覆盖两个附加的行,而是让它只覆盖最后附加的行?

【问题讨论】:

  • 澄清一下,“示例所需的输出 CSV”不完整,对吧?我认为应该是 9 行,而不是 5 行。

标签: python list csv overwrite


【解决方案1】:

为了重申你的目标,下面的 sn-p 创建了一个新的 csv,

  1. 为原始行写入一行,然后,
  2. 用起始值和字符串写入一行。

如果该评估有效,我通常一次打开一个文件以最大程度地减少我的认知负担。

with open('input.csv','r') as file_handle:
    file_content = file_handle.read().split('\n')
with open('output.csv','r') as file_handle:
    for index,line in enumerate(file_content):
        if index==0:
            print(line)
            file_handle.write(line)
        else:
            line_as_list = line.split(',')
            print(line_as_list)
            file_handle.write(line)
            print(line_as_list[0], line_as_list[-1])
            file_handle.write(str(line_as_list[0])+","+str(line_as_list[-1]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    相关资源
    最近更新 更多