I have a text file which does not confirm to standards. So I know the (end,start) positions of each column value.
Sample text file :
# # # #
Techy Inn Val NJ
Found the position of # using this code :
1 f = open('sample.txt', 'r')
2 i = 0
3 positions = []
4 for line in f:
5 if line.find('#') > 0:
6 print line
7 for each in line:
8 i += 1
9 if each == '#':
10 positions.append(i)
1 7 11 15 => Positions
So far, so good! Now, how do I fetch the values from each row based on the positions I fetched? I am trying to construct an efficient loop but any pointers are greatly appreciated guys! Thanks (:
Off the top of my head:
Update with tested, fixed code:
Input file:
Debug output:
Robustification notes:
#in the header line; it doesn’t need the header line to be padded out with spaces or anything else.#.Final(?) update: Leapfrooging @gnibbler’s suggestion to use
slice(): set up the slices once before looping.