Skip to content Skip to sidebar Skip to footer

Using First Row As Variable With Python

I want to change this piece of code where indicated to be more dynamic and specific. I would like to use the first row information in each column as a header that substitutes 'numA

Solution 1:

You can take advantage of the fact that open in python returns a generator. f.readline() gets you the next available line in the file. It also causes the generator to move to the next line, so in the list comprehension, it'll skip the line you've already read with f.readline(). (See documentation here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects)

with open(inputPath, "r") as f:
    strip = str.strip
    split = str.split
    titles = split(strip (f.readline())
    data = [split(strip (line)) for line in f]

Solution 2:

You are not exactly formatting your desired title to output. Here

for e inrange(numAtts):
        print"@ATTRIBUTE att{0} NUMERIC".format(e)

you are merely formatting value of e to output. You need to access the data[0] here.

for e inrange(numAtts):
        print"@ATTRIBUTE att'[{0}]'' NUMERIC".format(dataa[0][e] )

And later for usage part you can exploit range/xrange to skip 0th index.

for e in range(1, numAtts):
    print",".join(data[e][0:])

Also I would suggest there is no need to store str methods in variables you can use method chaining to get desired value. Instead of this:

data = [split(strip (line)) for line in f]

use this:

data = [line.strip().split() for line in f]

*********** Edited to include this option ***********

next also permits the skipping of the first row, beginning the data segment, therefore with the second.

next(iter(data))
for item in data[1:]:
    print",".join(item[0:])

Post a Comment for "Using First Row As Variable With Python"