Python rewriting instead of appending

2019-09-14 03:45发布

问题:

I have two csv files result.csv and sample.csv.

result.csv

M11251TH1230 
M11543TH4292 
M11435TDS144

sample.csv

M11435TDS144,STB#1,Router#1 
M11543TH4292,STB#2,Router#1 
M11509TD9937,STB#3,Router#1
M11543TH4258,STB#4,Router#1

I have a python script which will compare both the files if line in result.csv matches with the first word in the line in sample.csv, then append 1 else append 0 at every line in sample.csv

It should look like M11435TDS144,STB#1,Router#1,1 and M11543TH4258,STB#4,Router#1,0 since M11543TH4258 is not found in result.csv

script.py

import csv
with open('result.csv', 'rb') as f:
    reader = csv.reader(f)
    result_list = []
    for row in reader:
        result_list.extend(row)


with open('sample.csv', 'rb') as f:
    reader = csv.reader(f)
    sample_list = []
    for row in reader:
        if row[0] in result_list:
            sample_list.append(row + [1])
        else:
            sample_list.append(row + [0])

with open('sample.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(sample_list)

sample output(sample.csv)if I run the script two times

M11435TDS144,STB#1,Router#1,1,1 
M11543TH4292,STB#2,Router#1,1,1
M11509TD9937,STB#3,Router#1,0,0
M11543TH4258,STB#4,Router#1,0,0

Every time I run the script, 1's and 0's are being appended in a new column sample.csv. Is there any way every time I run the script, I can replace the appended column instead of increasing columns.

回答1:

you write to the sample.csv and then you use it as input file, with the additional column. That's why you have more and more 1's and 0's in this file. Regards, Grzegorz