Reputation: 65
So I have to write a code that first reads in the name of an input file, followed by two strings representing the lower and upper bounds of a search range. The file should be read using the file.readlines() method. The input file contains a list of alphabetical, ten-letter strings, each on a separate line. The program should output all strings from the list that are within that range (inclusive of the bounds).
The text file (input1.txt) contains:
aspiration
classified
federation
graduation
millennium
philosophy
quadratics
transcript
wilderness
zoologists
so for example, if i input:
input1.txt
ammoniated
millennium
the output should be:
aspiration
classified
federation
graduation
millennium
So far, I tried:
# prompt user to enter input1.txt as filepath
filepath = input()
start = input()
end = input()
apending = False
out = ""
with open(filepath) as fp:
line = fp.readline()
while line:
txt = line.strip()
if(txt == end):
apending = False
# how do I make it terminate after end is printed??
if(apending):
out+=txt + '\n'
if(txt == start):
apending = True
line = fp.readline()
print(out)
However, it does not seem to output anything. Any help debugging or fixing my code is greatly appreciated~
Upvotes: 1
Views: 897
Reputation: 388
You can exit out of a for loop by using the keyword break
for example
for x in range(50):
if x > 20:
break;
else:
print(x);
Upvotes: 0
Reputation: 2272
This can be done by comparing strings using the <=
and >=
operators, and then filtering the words that match the lower and upper bounds criteria.
As said in this article, "Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller."
f = open('input.txt')
words = f.readlines()
lower_bound = input('Set the lower bound for query')
upper_bound = input('Set the upper bound for query')
result = [word.strip() for word in words if lower_bound <= word.strip() <= upper_bound]
print(result)
f.close()
output for print(result)
, with the input you provided:
['aspiration', 'classified', 'federation', 'graduation', 'millennium']
Upvotes: 0
Reputation: 23139
None of the strings in the input is equal to ammoniated
, therefore txt == start
is never true, therefore apending
is never set to True
, therefore out += txt + '\n'
is never executed, therefore print(out)
prints an empty string at the end.
You should use <
or >
to compare the strings from the input with start
and end
. They are not supposed to be exact matches.
Upvotes: 0
Reputation: 824
here is the code:
# prompt user to enter input1.txt as filepath
filepath = input()
start = input()
end = input()
# apending = False
# out = ""
with open(filepath) as fp:
while True:
line = fp.readline()
if not line:
break
txt = line.strip()
if txt >= start and txt <= end:
print(txt)
if txt > end:
break
Upvotes: 1