简体   繁体   English

Python CSV搜索脚本

[英]Python csv search script

I wish to write a Python script which reads from a csv. 我希望编写一个从csv读取的Python脚本。 The csv comprises of 2 columns. CSV由2列组成。 I want the script to read through the first column row by row and find the corresponding value in the second row. 我希望脚本逐行读取第一列,并在第二行中找到相应的值。 If it finds the value in the second row I want it to input a value into a third column. 如果它在第二行中找到值,我希望它在第三栏中输入一个值。

example of output 输出示例

Any help with this would be much appreciated and I hope my aim is clear. 任何帮助,将不胜感激,我希望我的目标是明确的。 Apologies in advance if it is too vague. 如果太含糊,请提前道歉。

this script read test.csv file and parse it an write to OUTPUT.txt 该脚本读取test.csv文件并将其解析为写入OUTPUT.txt

f = open("test.csv","r")
d={}
s={}
for line in f:
        l=line.split(",")
        if not l[0] in d:
                d[l[0]]=l[1].rstrip()   
                s[l[0]]=''
        else:
                s[l[0]]+=str(";")+str(l[1].rstrip())

w=open("OUTPUT.txt","w")
w.write("%-10s %-10s %-10s\r\n" % ("ID","PARENTID","Atachment"))
for i in d.keys():
        w.write("%-10s %-10s %-10s\r\n" % (i,d[i],s[i]))

f.close()
w.close()

example: 例:

input: 输入:

ID         PARENTID   Atachment 
000001     sasa       ;sasa2;sas4
1023265    333                  
1          123        ;333;asas;333;ss
3                               
2          456                  
0221212  

OUTPUT: 输出:

 ID PARENTID Atachment 000001 sasa ;sasa2;sas4 1023265 333 1 123 ;333;asas;333;ss 3 2 456 0221212 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM