I have to print a text file (cities) in a While Loop but it goes to infinity
filehandle=open("cities.txt", "r")
f = filehandle.readline()
while f != "":
print(f)
filehandle.close()
while f != "":
That says that if f isn't an empty string, keep printing. So if cities.txt has anything in it, you print forever. And I think only print the first line again and again.
What does the assignment say exactly?
The assignment is to make a menu and the first option of that menu is to print the list of cities.
So how would i use the loop to print the text file using .readline(). How would it print forever? If f has come to a line which is empty wouldnt it stop?
f = open('cities.txt', r)
while True:
line = f.readline()
print(line)
if not line:
break
f.close()
Your
readline()
needs to be inside the loop or it never changes. If it never changes then it can never be an empty line.
(Feb-08-2020, 04:43 AM)Nomex Wrote: [ -> ]How would it print forever? If f has come to a line which is empty wouldnt it stop?
No it would not stop,it always read whole file to the end using while or for loop.
A better way,so can iterate over file object line bye line(do not need
readline()
).
with open('cities.txt') as f:
for line in f:
print(line.strip())
Example how stop(break out of loop) if there is a empty line.
with open('cities.txt') as f:
for line in f:
if line in ('', '\n'):
break
print(line.strip())
(Feb-08-2020, 09:21 PM)snippsat Wrote: [ -> ]A better way,so can iterate over file object line bye line(do not need readline()).
I think the assignment specifies readline().
The problem of infinity was there because i did not write f=f.readline() in the loop again. After that it worked perfectly. Thanks by the way!
(Feb-10-2020, 01:42 PM)Nomex Wrote: [ -> ]The problem of infinity was there because i did not write f=f.readline() in the loop again. After that it worked perfectly. Thanks by the way!
Although it works, it's better to look at @
snippsat example, because it's much better and pythonic than what you do