0

my program will import a file created by user having maximum of 15 lines of text in it(examples below)

#ID #value1 # value2
445 4 9000 
787 2 4525 
405 4 3352 
415 1 2854 
455 2 5500 

r The program then filter all the lines that have #value 1 larger than 2 and #value 2 larger than 3000 and print out their #ID, ignoring the rest.

here's what i have done so far

filename = ('input.txt')
infile = open(filename, 'r')
list_id = []
list_value1 = []
list_value2 = []
masterlist = []
for line in infile:
id, value1, value2 = line.split()
list_id.append(id)
list_value1.append(value1)
list_value2.append(value2)
masterlist.append(list_id)
masterlist.append(list_value1)
masterlist.append(list_value2)

#filtering part
sort = [i for i in masterlist[1] if i > 2 ] and [p for p in masterlist[2] if p > 3000]

#do something here to print out the ID of the filtered lines
3

1 Answer 1

3

Using your code as a starting point:

filename = ('input.txt')
infile = open(filename, 'r')
ids = []
for line in infile:
    id, value1, value2 = line.split()
    if int(value1) > 2 and int(value2) > 3000:
        ids.append(id)

Put in exception handling for non-integer values as needed.

1
  • 1
    @user2958069: The filename = 'input.txt' is enough. No need for parentheses. The infile should also be closed. Or you can use with open(filename) as infile: and the infile will be closed automatically.
    – pepr
    Nov 28, 2013 at 20:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.