I am trying to do a simple process on python, I know there is an answer out here on how to achieve this, but I can't seem to find it.
Python should make selection from a list of data on a txt file, but in an ordered form. Say it would pick the first value when prompted, then the second value,and so on until the list is exhausted.
Is there a way to achieve this without random? The only way I have seen so far are randomly, and randomly without/with replacement. The order of choice is very important here.
import random
with open ("questions.txt","r") as f:
question = f.readlines()
post = (random.choice(question).strip())
print (post)
The code above only do so randomly and not what I want, I want it ordered and stop when the list is finished.
with open ("questions.txt","r") as f:
question = f.readlines()
for each in question:
print(each.strip())
or if you want to have more control, you can use next
on an Iterator (and handle the end-of-iteration exception):
with open ("questions.txt","r") as f:
questions = iter(f.readlines())
while True:
try:
question = next(questions)
except StopIteration:
# no more questions
else:
# handle `question`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.