Reputation: 139
for line in file:
line = int(line)
if line <= maximumValue:
counter = counter + 1
if line >= minimumValue:
counter = counter + 1
print (int(line))
file.close()
I am taking a file of a list of numbers, say from 1 to 10. I want to list the max and min values, as well as the values between the min and max. When I have my program open the file, it only prints out the total amount of numbers, and doesn't eliminate those that are higher then the max or lower then the min. What am I missing here and what can I do to correct it?
Upvotes: 0
Views: 366
Reputation: 142166
An example using a handy property of xrange
:
MIN = 3
MAX = 7
valid_range = xrange(MIN, MAX+1)
with open('file') as fin:
nums = (int(line) for line in fin)
valid_vals = [num for num in nums if num in valid_range]
# or if you just want count of valid values
count = sum(1 for num in nums if num in valid_range)
print valid_vals, len(valid_vals)
Upvotes: 0
Reputation: 298206
Python supports normal (readable) inequalities:
numbers = []
counter = 0
with open('filename.txt', 'r') as handle:
for line in handle:
number = int(line)
if minimumValue <= number <= maximumValue:
numbers.append(number)
counter += 1
print(counter)
print(numbers)
Also, use with
to open files. You don't have to worry about closing them afterwards.
Upvotes: 2