1

I am working out of a text file (call it user.txt for now) and would like to be able to skip the first item [0] in each row, use the following numbers in an equation [3:4], and then spit out my equated answer from that specific row and add it to the end of the row [5] for each individual line going down the list. But I am struggling with skipping [0] and then a following up with my equation and spitting out my answer. I am new to python and am looking for suggestions for a good structure on how to do this. Below is a sample of my list from my user.txt.

['Port', '1853282.679', '1673876.66', '1 ', '2']
['Bruns', '1963178.059', '1695301.229', '0 ', '1']
['Tops', '2092564.258', '1666785.835', '5 ', '6']
['Brave', '3464227.016', '1699924.786', '1 ', '1']
['Crew', '3056933.525', '1688585.272', '9 ', '3']
['Hann', '3180151.244', '1670897.027', '7 ', '3']
['Luke', '3403469.566', '1694894.58', '0 ', '1']
.......
Phil
  • 33
  • 2

2 Answers2

0

Well, if you're already reading the lines, you can parse each line like this:

line = "['Port', '1853282.679', '1673876.66', '1 ', '2']"
line = line[1:-1] # Line is now "'Port', '1853282.679', '1673876.66', '1 ', '2'"
line = line.split(',') # Line is now a list containing the former comma separated params

Now you can use the parameters like line[0], line[1] and so on

FBidu
  • 972
  • 9
  • 21
0

Phil, try to translate your requirements literally in code:

#coding:utf-8

##I am working out of a text file (call it user.txt for now)
user_txt = ('''['Port', '1853282.679', '1673876.66', '1 ', '2']
['Bruns', '1963178.059', '1695301.229', '0 ', '1']
['Tops', '2092564.258', '1666785.835', '5 ', '6']
['Brave', '3464227.016', '1699924.786', '1 ', '1']
['Crew', '3056933.525', '1688585.272', '9 ', '3']
['Hann', '3180151.244', '1670897.027', '7 ', '3']
['Luke', '3403469.566', '1694894.58', '0 ', '1']'''
    .replace('[','')
    .replace(']','')
    .replace(' ','')
    .replace("'",''))
lines = user_txt.split('\n')
##and would like to be able to skip the first item [0] in each row,
rows = [line.split(',')[1:] for line in lines]
##use the following numbers in an equation [3:4],
equations = [int(row[2]) + int(row[3]) for row in rows]
##and then spit out my equated answer from that specific row
print equations
##and add it to the end of the row [5] for each individual line going down the list.
print [row + [int(row[2]) + int(row[3])] for row in rows]
Alex Yu
  • 3,412
  • 1
  • 25
  • 38
  • Thanks for the suggestion and this would work but I have a txt file with 100 rows and I need to pull from the txt file. Any suggestions for pulling from a txt file? – Phil Dec 24 '15 at 18:09