Zomgosh
Zomgosh

Reputation: 1

using data from a txt file in python

I'm learning python and now I'm having some problems with reading and analyzing txt files. I want to open in python a .txt file that contains many lines and in each line I have one fruit and it's price.

I would like to know how to make python recognize their prices as a number (since it recognizes as a string when I use readlines()) so then I could use the numbers in some simple functions to calculate the minimum price that I have to sell the fruits to obtain profit.

Any ideas of how to do it?

Upvotes: 0

Views: 4894

Answers (3)

Shawn Chin
Shawn Chin

Reputation: 86864

Assuming your values are space-separated, you can read in your file into a list of tuples using:

# generator to read file and return each line as a list of values
pairs = (line.split() for line in open("x.txt"))  
# use list comprehension to produce a list of tuples
fruits = [(name, float(price)) for name, price in pairs] 

print fruits
# will print [('apples', 1.23), ('pears', 231.23), ('guava', 12.3)]

Note that float() was used to convert the second value (price) from str to a floating point number.

See also: list comprehension and generator expression.


To make it easy to look up prices for each fruit, you can convert your list of tuples into a dict:

price_lookup = dict(fruits)

print price_lookup["apples"]
# will print 1.23

print price_lookup["guava"] * 2
# will print 24.6

See: dict().

Upvotes: 1

Gordon Broom
Gordon Broom

Reputation: 300

I had the same problem when I first was learning Python, coming from Perl. Perl will "do what you mean" (or at least what it thinks you mean), and automatically convert something that looks like a number into a number when you try to use it like a number. (I'm generalizing, but you get the idea). The Python philosophy is to not have so much magic occurring, so you must do the conversion explicitly. Call either float("12.00") or int("123") to convert from strings.

Upvotes: 0

NPE
NPE

Reputation: 500357

If the name and the price are separated by a comma:

with open('data.txt') as f:
  for line in f:
    name, price = line.rstrip().split(',')
    price = float(price)
    print name, price

Upvotes: 1

Related Questions