You've got a couple problems:
- You've got two loops, but the file is exhausted by the first loop so the second loop never runs (it finds
names
empty and bypasses the body of the loop)
- You're testing for
endswith('s')
, but almost every line would actually end with a newline, which you haven't stripped
As a minimal fix for both problems (maintaining the behavior of two loops so you print the lines the end with s
separately and first):
with open("names.txt") as names:
for loop in names:
loop = loop.rstrip('\n') # Remove trailing newline, if any, to avoid doubled
# newline on print and make test work
if loop.endswith('s'):
print(loop)
names.seek(0) # Reset file pointer to beginning of file
for loop in names:
loop = loop.rstrip('\n') # Same strip as in prior loop
if loop.startswith('A'):
print(loop)
If any passing line being printed on a single pass is fine, and you don't need lines beginning with A
and ending with s
to be printed twice, you can simplify to:
with open("names.txt") as names:
for loop in names:
loop = loop.rstrip('\n') # Remove trailing newline, if any, to avoid doubled
# newline on print and make test work
if loop.startswith('A') or loop.endswith('s'):
print(loop)