How To Extract Specific Columns From A Space Separated File In Python?
I'm trying to process a file from the protein data bank which is separated by spaces (not \t). I have a .txt file and I want to extract specific rows and, from that rows, I want to
Solution 1:
If you already have extracted the line, you can split it using line.split()
. This will give you a list, of which you can extract all the elements you need:
>>> test='HELIX 2 2 CYS A 97'>>> test.split()
['HELIX', '2', '2', 'CYS', 'A', '97']
>>> test.split()[3]
'CYS'
Solution 2:
Have a look at the CSV library. https://docs.python.org/2/library/csv.html The following code should do the trick
>>>import csv>>>withopen('my-file.txt', 'rb') as myfile:... spamreader = csv.reader(myfile, delimiter=' ', )...for row in spamreader:...print row[3]
Solution 3:
Is there a reason you can't just use split?
for line in open('myfile'):
if line.startswith('HELIX')
cols = line.split(' ')
process(cols[3], cols[5], cols[6], cols[8])
Solution 4:
you can expend the key words as you want. the result is list contained line with key words you can do further process of result to get what you want
withopen("your file") as f:
keyWords = ['HELIX','SHEET','DBREF']
result = [ line for line in f for key in keyWords if key in line]
Post a Comment for "How To Extract Specific Columns From A Space Separated File In Python?"