0

I have a txt file which looks like this:

    100.00   gasoline
    20.00    lunch
    12.50    cigarettes

I want to take only the numbers (100.00, 20.00, 12.50) and append them to a list, how can I do it? I tried with:

    tot_us = []
    for float in us_file:
        tot_us.append(float)

When I print the list i get:

  ['100.00\tgasoline\n', '20.00\tlunch\n', '12.50\tcigarettes\n']

I was expecting:

  ['100.00', '20.00', '12.50']

I know is a noob attempt, how can I solve this?

RingK
  • 83
  • 12

2 Answers2

0

You need to use .split() to break up each line into two sections:

total_us = []

with open('somefile.txt') as f:
    for line in f:
        if line.strip():
            bits = line.split('\t')
            total_us.append(bits[0])

print(total_us)

Or, you can use the csv module:

import csv

with open('somefile.txt') as f:
    reader = csv.reader(f, delimiter='\t')
    total_us = [row[0] for row in reader]

print(total_us)
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • Thanks, it worked, I then used float(i) to convert them, append them to another list and do maths. I prefer method 1 since there's no need to import anything! – RingK Feb 03 '16 at 15:50
0

You could also identify the position of the tab and then use slicing:

tot_us = []
for line in us_file:
    tab_pos = line.index('\t')
    float = line[:tab_pos]
    tot_us.append(float)

For more information about slicing see this answer.

Community
  • 1
  • 1
simon
  • 2,896
  • 1
  • 17
  • 22