Python重写而不是追加 [英] Python rewriting instead of appending

查看:367
本文介绍了Python重写而不是追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个csv文件result.csv和sample.csv。

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

result.csv

result.csv

M11251TH1230 
M11543TH4292 
M11435TDS144

csv

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

我有一个python脚本,如果result.csv中的行与sample.csv中的第一个单词匹配,然后append 1 else append 0在sample.csv

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

它应该看起来像M11435TDS144,STB#1,路由器#1,1和M11543TH4258,STB#4,路由器#1,0,因为M11543TH4258在result.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

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.csv)如果我运行脚本两次

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

每次运行脚本时,1和0将被添加到一个新列sample.csv中。每次运行脚本时都有办法,我可以替换附加的列而不是增加列。

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.

推荐答案

sample.csv ,然后将其用作输入文件,使用附加列。这就是为什么你有越来越多的1和0在这个文件。
谨慎,Grzegorz

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

这篇关于Python重写而不是追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆