Solved

Python CSV help - matching from 1 field, outputs information from another field

Posted on 2014-10-03
8
230 Views
Last Modified: 2014-10-06
Right now I am working with a csv file that I am basically trying to use conditions from 1 column to out put the information from another column. The csv looks like this:

typ1,typ2,type3
aaa,unneed=trap,121
aaa,unneed=strap,222
aaa,unneed=cap,212
bbb,unneed=lock,112
bbb,unneed=stock,346
bbb,unneed=rock,333
ccc,unneed=vent,456
ccc,unneed=bent,444
ccc,unneed=sent,478

What I would like to do is to basically filter based on the 1st field, and have the output be from field 2.  This is the code I have so far:

for line in csv_file:
    altl = line['typ1']
    #cOut = altl + ', ' + line['typ2'] + '\n'
    cn = line['typ2'].split("=")[1] + '\n'
    #the next 3 lines were to test the output
   # if altl == 'aaa':
        #print cn
      #print 'this needs to be an array:' + '\n' + cn

The next portion of the code is where I get stuck. I know how to do this in LUA, but I really really need to get better at python. In LUA, I would loop through, something like this

i = 1,#endofsameitems

while i == altl do
stuff with cn
 end

Essentially I need the output to be:

print 'elements belonging to' + "'" altl "'" + ' :' + '\n' + cn

so that it looks something like this.

elements belonging to 'aaa':
trap
strap
cap

How exactly can I go about that?
0
Comment
Question by:shellee1983
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 45

Expert Comment

by:aikimark
ID: 40361439
Running this script:
import csv

def main(parmT1):
    with open("C:\Users\AikiMark\Downloads\Q_28531163.csv", "r") as f:
        csvdata=csv.DictReader(f)
        print "Records belonging to '" + parmT1 + "' :"
        for rec in csvdata:
            if rec["typ1"] == parmT1:
                print rec["typ2"].split("=")[1]

if __name__ == '__main__':
    main("bbb")

Open in new window

against your sample data, produces the following output:
Records belonging to 'bbb' :
lock
stock
rock

Open in new window

0
 

Author Comment

by:shellee1983
ID: 40361805
Hi, Thanks for the awesome help, but I am still stuck. I see that you used the actual information in the csv to filter it but i need to be able to create a loop that runs through the whole file.

So for instance, say that I want it to write to a file. SOmething like this:

varToFilter = rec["typ1"]
k = "Records belonging to '" + parmT1 + "' :"
        while true:
		i = 0
		varToFilter [i] == varToFilter[i] 
		writeOut(k)
		if varToFilter [i] =! rvarToFilter [i]
		pass_

Open in new window


So essentially, there would be 3 files after the csv is run as in

this would be written to a file:
Records belonging to 'bbb' :
lock
stock
rock

this would be written to another file:
Records belonging to 'aaa' :
trap
strap
cap

and this would be written to a third file:
Records belonging to 'aaa' :
trap
strap
cap

how would I got about doing something like that?

Also, where is a good resource to find this kind of information without asking?
0
 
LVL 45

Expert Comment

by:aikimark
ID: 40361816
is it safe to assume that the list is already in typ1 sorted order?
0
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 

Author Comment

by:shellee1983
ID: 40364036
yes, but essentially the order really does not matter.
0
 
LVL 45

Expert Comment

by:aikimark
ID: 40364042
the order really does not matter
The order matters if you are selecting algorithms.

What file names do you need to produce?
0
 

Author Comment

by:shellee1983
ID: 40364287
The order matters if you are selecting algorithms.
I see what you are saying here, and yes they would be put into order first. The names of the files can be the field typ1.
0
 
LVL 45

Accepted Solution

by:
aikimark earned 500 total points
ID: 40364517
Then the code will resemble this:
import csv

def main():
    with open("C:\Users\AikiMark\Downloads\Q_28531163.csv", "r") as f:
        csvdata=csv.DictReader(f)
        prevKey=None
        for rec in csvdata:
            if rec["typ1"] == prevKey:
                o.write( rec["typ2"].split("=")[1]+"\n")
            else:
                try:
                    o.close
                except:
                    pass
                prevKey = rec["typ1"]
                o=open('C:\\Users\\AikiMark\\Downloads\\' + prevKey + '.txt', 'w')
                o.write("Records belonging to '" + prevKey + "' :"+"\n")
                o.write( rec["typ2"].split("=")[1]+"\n")

if __name__ == '__main__':
    main()

Open in new window

0
 

Author Closing Comment

by:shellee1983
ID: 40364849
Thank you so much! I am struggling converting from LUA :(
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
powershell md/mkdir/New-item   -Quiet 10 244
Python filter object attributes 2 42
Adding a countdown to HTA 12 99
size of file 1 24
Article by: Nadia
Suppose you use Uber application as a rider and you request a ride to go from one place to another. Your driver just arrived at the parking lot of your place. The only thing you know about the ride is the license plate number. How do you find your U…
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question