1

My goal is to read in a file, and return the corresponding information that the user has asked for. For example my text file looks like this (it represents the year and the students heights from that year):

2013

5.5 6.3 4.0 5.2 5.1

2014

4.6 4.8 5.3 5.6 6.0

2015

3.8 4.9 6.0 5.8 5.7

Basically if I enter 2013, I want it to return the list of heights that correspond to that year (the line below). But I can't event get it to print back the list of strings. Some help would be great.

#read in text file
f = open("students.txt")
#ask for student year
year = input("Enter the year for the data you want to receive:")
#check to see if year is avialble
line = f.readline()
while True:
    line = f.readline().split()
    if line:
        if line == year:
            print(line)
    else:
        break
        print("No data")

6 Answers 6

1

A simple approach is to read all lines of a file into a list, then find the index in that list based on the year you want, and get the next line.

with open('students.txt', 'r') as f:
    data = [i.strip() for i in f]   # strip trailing space

year = input("Enter year: ")
try:
    # find index, get the next line
    line = data[data.index(year) + 1] 
    # split on whitespace, apply float()
    item_list = [float(i) for i in line.split()]
except ValueError:  # raised if year not found
    print("No relevant data")
Sign up to request clarification or add additional context in comments.

Comments

1

Print next not empty line after line that is equal required year.

year = "2013"

with open("students.txt") as f:
    stop = False
    for line in f:
        line = line.rstrip("\n")
        if line == year:
            stop = True
        else:
            if line and stop:
                print line.split()
                break

    if not stop:
        print "No data for year {}.".format(year)

Comments

1

Instead try reading all the entries into a dictionary. Then its simple to query by year.

def readentries(f):    
    # read until we get `StopException` i.e. end of file
    while True:
        try:
            # take two lines from the file and strip newlines
            # and split heights by spaces to give a list of heights
            yield next(f).strip(), next(f).strip().split()
        except StopIteration:
            # break out of the infinite while loop
            break

with open('heights.txt') as f:
     entries = dict(readentries(f))

year = input("Enter the year for the data you want to receive: ")

# query dict for supplied entry
if year in entries:
    print('for year %s we have heights %s ' % (year, ', '.join(entries[year])))
else:
    print('no data')

You may want to convert the heights to float variables. This would be easy to add.

Comments

0

When you do f.readline().split(), you get a list. So for the first line, you would have something like line == ['2013']. On the other hand, year is a string. So if the user put in 2013, type(year) == <class 'str'> while type(line) == <class 'list'>. Because they are never equal to each other, the if clause is never True and the line never gets printed.

#read in text file
f = open("students.txt")
#ask for student year
year = input("Enter the year for the data you want to receive:")
#check to see if year is available
for line in f.readlines():
    if year in line:
        f.readline()
        print ( f.readline() )
        break

Above code wouldn't work if there's a student whose height is over 2,000, I suppose.

Comments

0

You can also build two lists and construct a dictionary by iterating over the lines of thhe file:

with open("grade.txt", "r") as file:
    year = []
    height = []
    for i in file:
        if len(i.strip("\n")) == 4:
            year.append(i.strip("\n"))
        elif i != "\n":
            height.append(i.strip("\n").split(" "))
    ydict = {year[i]: height[i] for i in range(len(year))}

print(ydict['2013'])

Comments

0

Since the data includes some blanks lines and tabs, you'll want to clean it up first. Then it's just a matter of added the even numbered rows (years) as keys (starting at zero) in a dictionary and the odd numbered rows (heights) as values in the dictionary.

year = input("Enter the year for the data you want to receive:")
with open("students.txt") as f:
    # read stripped file lines into list keeping only those that contain data
    data = [line.strip() for line in f.readlines() if line.strip() != '']
# build a dict from the data using list slicing to get the years (keys) and heights (values)
data_dict = dict(zip(data[0::2], data[1::2]))
# print the heights if the year exists otherwise 'No data.'
print(data_dict.get(str(year)) if data_dict.get(str(year)) else 'No data.')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.