0

I'm absolute beginner in python, and I'd like to get field i.e. from 2nd column, 3rd row from text file like this:

176a AUGCACGUACGUA ACGUA AGUCU
156b GACUACAUGCAUG GCAUA AGCUA
172e AGCUCAGCUAGGC CGAGA CGACU

(text is separated by spaces). is there any simple way to do that?

Alex K.
  • 171,639
  • 30
  • 264
  • 288
Asia
  • 17
  • 5
  • possible duplicate of [Python library for parsing space delimited files](http://stackoverflow.com/questions/13773332/python-library-for-parsing-space-delimited-files) and many others, google fu: *python parse space delimited text file* – Alex K. Jun 17 '15 at 11:48

3 Answers3

0

if your file isn't too big I would read it once then split each line and get the part that I want :

with open(myfile) as file_in : 
    lines = file_in.readlines()

third_line = lines[2]
second_column = third_line.split(' ')[1]
print second_column
Azurtree
  • 369
  • 4
  • 11
0

You could split the text and have a list of lists, where each sub list is a row, then pluck whatever you need from the list using rows[row - 1][column - 1].

f = open('test.txt', 'r')
lines = f.readlines()
f.close()
rows = []
for line in lines:
    rows.append(line.split(' '))
print rows[2][1]
heinst
  • 8,520
  • 7
  • 41
  • 77
0

If I have a file test which contains your example data the following will doing the job:

def extract_field(data, row, col):
    '''extract_field -> string

    `data` must be an iterable file object or an equivalent
    data structure which elements contains space delimited
    fields.
    `row` and `col` declares the wished field position which
    will be returned. '''
    # cause first list element is 0
    col -= 1
    # jump to requested `row`
    for _ in xrange(row):
        line = next(data)
    # create list with space delimited elements of `line`
    # and return the `col`'s element of these list
    return line.split()[col]

Use it like this:

>>> with open('test') as f:
...     extract_field(f, row=3, col=2)
... 
'AGCUCAGCUAGGC'
mutetella
  • 192
  • 1
  • 8