Reputation: 23
I need to read from a text file that looks like this:
football 1
basketball 2
hockey 0
tennis 2
...
where there are x number of lines, each one with a sport and a number. I'm given a sport and i have to save the number of that sport in a variable, but i cant find a good way to do it.
Upvotes: 0
Views: 2287
Reputation: 2447
There're a few options here. The simplest is to just iterate through the file object using standard python.
# This will only get the first occurrence
with open("sportfile.txt", "r") as f:
for line in f:
curr_sport, num = line.split()
if curr_sport==sport:
break
If you have multiple occurrences you can store the numbers in a list - or you can sum them if you don't need specificity... depends on the problem at hand.
sport = 'football' # for example
football_nums = []
with open("sportfile.txt", "r") as f:
for line in f:
curr_sport, num = line.split()
if curr_sport==sport:
football_nums.append(num)
See the docs "https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" for info on file handles in python.
If you need to translate the file into a python structure that you can query to find any sport and corresponding number you could use pandas (might be overkill but I love pandas :-))
df = pd.read_csv('sportfile.txt', sep = ' ')
df.columns = ['sport', 'num']
df[df.sport=='football'] # returns all rows where the sport is football.
pandas .read_csv()
is crazy detailed and powerful: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
Upvotes: 2
Reputation: 432
Feel free to try this. Just tested the quick sample in shell.
import sys
if __name__ == '__main__':
key = "football"
for line in sys.stdin:
sport, number = line.split()
if sport == key:
print "{}, {}".format(sport, number)
break
else:
print "{} not found".format(key)
Upvotes: 0