Skip to content Skip to sidebar Skip to footer

How To Create A List To Select Index?

I have this code to check indexes in a file to see if they match, but to start off I am having trouble being able to select an index. What do I have to do in order to be able to do

Solution 1:

Try using line.split(",") to split the line by the commas, then strip out the quotation marks by slicing the result.

Example:

>>>line = '"190","Windows 2000","2000","609"'>>>sliced = line.split(',')>>>print sliced
['"190"', '"Windows 2000"', '"2000"', '"609"']
>>>first_item = sliced[0][1:-1]>>>print first_item
190

...and here's the whole thing, abstracted into a function:

def get_item(line, index):
    return line.split(',')[index][1:-1]

(This is assuming, of course, that all the items in the line are divided by commas, that they're all wrapped by quotation marks, that there's no spaces after the commas (although you could take care of that by doing item.strip() to remove whitespace). It also fails if the quoted items contains commas, as noted in the comments.)

Solution 2:

And if you try using split() to split each comma and return first value? Try this.

Solution 3:

[0] applied to a string only returns the first character.

You want the first item of a comma-separated list. You could write your own parsing code, or you could use the csv module which already handles this.

import csv

defget_first_row(fname):
    withopen(fname, 'rb') as inf:
        incsv = csv.reader(inf)
        try:
            row = incsv.next()
        except StopIteration:
            row = [None]
        return row

defcheckOS():
    fid = get_first_row("C:/Python/NSRLOS.txt")[0]
    fhand = get_first_row("C:/Python/sha_sub_hashes.out")[0]
    print fid

Solution 4:

csv.reader would be a good start.

import csv
from itertools import izip

withopen('file1.csv') as fid, open('file2.csv') as fhand:
    fidcsv = csv.reader(fid)
    fhandcsv = csv.reder(fhand)
    for row1, row2 in izip(fidcsv, fhandcsv):
        print row1, row2, row[1] # etc...

Using csv.reader will handle CSV formatted files better than pure str methods. The izip will read line1 then 2, then 3 etc.. from both files (it will stop at the shortest number of rows in the file though), then line2 from both files etc... (not sure if this is what you want though). row1 and row2 will end up being a list of columns, and then just index if row1[0] == row2[0]: or whatever logic you wish to use.

Post a Comment for "How To Create A List To Select Index?"