Python rewriting instead of appending

纵然是瞬间 提交于 2019-12-13 08:27:37

问题


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



来源:https://stackoverflow.com/questions/39751095/python-rewriting-instead-of-appending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!