get the first row in multiple files in python

Viewed 191

I'm trying to iterate over files to get the first line and put it in a database. The problem that I have is that i can't figure out how to only read 1 row. Now it runs over all the rows while I only need 1 row per file.

The files looks like this:

batch_name  sample_barcode  pool_barcode    pool_type   pooling_volume_ul   pooling_comments
NIPT20200304    0101002253  PT2129764   A   2.0 
NIPT20200304    0109011474  PT2129764   A   17.66   

And my code is currently this:

pools = []
for files in library:
    with open(files, 'r') as f:
        next(f)
        reader = csv.reader(f, delimiter='\t')
        for row in reader:
            print("row: ", row)
            pools.append(row)
print("pools", pools)

with the for row in reader, it shows me all the rows, and with row[0], I only get the first column, but still get all the rows. i tried f.readline.().rstrip() but then I don't know where to put the delimiter as "\t" shows up in the pools variable instead of a space.

3 Answers

I got what I wanted thanks with this:

#read over the pool_report files and get the first line
pools = []
for files in library:
    with open(files, 'r') as f:
        next(f)
        data = f.readline().strip()
        values = data.split()
        pools.append(values)
print("pools: ", pools)

Try to call next(reader) instead of next(f):

pools = []
for files in library:
    with open(files, 'r') as f:
        reader = csv.reader(f, delimiter='\t')
        next(reader, None)
        for row in reader:
            print("row: ", row)
            pools.append(row)
print("pools", pools)

You dont need teh last for loop, like below

pools = []

for files in library:
    with open(files, 'r') as f:
        next(f)
        reader = csv.reader(f, delimiter='\t')
        pools.append(next(reader))
        
print("pools", pools)
Related