在For循环中插入下一行

时间:2019-09-13 15:42:41

标签: python python-2.7

我想在我的for循环中添加下一行,目前发生的是,由于它位于for循环中,因此所有数据都存储在一个数组中,一旦我在代码末尾编写了它,它打印为一行。

fields = []
new_rows_list = []

file1 = open('CSV_sample_file.csv','rb')
reader = csv.reader(file1)

fields = reader.next()

for row in reader:
    for column in row:
        cellValue = column
        new_row = find_and_mask_cc(cellValue)
        new_rows_list.append(new_row)
file1.close()

file2 = open('CSV_sample_file2.csv', 'wb')
writer = csv.writer(file2)

writer.writerow(fields)
writer.writerow(new_rows_list)

file2.close()

这是我得到的:

Created_User_ID__c,BRAND_Type__c,Migration_Remarks__c
EMSPDGBELNAS,test1,411111XXXXXX1111,EMSPDGCAJAPIN,test2,511111XXXXXX1111,EMSPDGNCRETES,test3,611111XXXXXX1111

我的预期的输出是这样的:

Created_User_ID__c,BRAND_Type__c,Migration_Remarks__c
EMSPDGBELNAS,test1,411111XXXXXX1111
EMSPDGCAJAPIN,test2,511111XXXXXX111
EMSPDGNCRETES,test3,611111XXXXXX1111

1 个答案:

答案 0 :(得分:1)

您要将所有列附加到同一列表new_rows_list上,并与writer.writerow(new_rows_list)一起写为一行。

您可以将new_rows_list设为列表列表,并使用writer.writerows进行输出:

...

for row in reader:
    new_row = []
    for column in row:
        cellValue = column
        new_row.append(find_and_mask_cc(cellValue))
    new_rows_list.append(new_row)
file1.close()

file2 = open('CSV_sample_file2.csv', 'wb')
writer = csv.writer(file2)

writer.writerow(fields)
writer.writerows(new_rows_list)

...

或者,您可以将通过writerows迭代的生成器表达式传递给reader,以便在您从输入中读取时将包含find_and_mask_cc转换为列的每一行写入输出,因此不需要将整个输入读入内存:

with open('CSV_sample_file.csv') as file1, open('CSV_sample_file2.csv', 'w', newline='') as file2:
    reader = csv.reader(file1)
    writer = csv.writer(file2)
    writer.writerow(next(reader))
    writer.writerows(map(find_and_mask_cc, row) for row in reader)

演示:https://repl.it/repls/SatisfiedSardonicExponents