When I use .readlines(), it gives me a list, can I separate this list into individual variables?
Many thanks if you can help me!
When I use .readlines(), it gives me a list, can I separate this list into individual variables?
Many thanks if you can help me!
Use a context manager:
with open(myfile, 'r') as f:
for line in f:
print(line)
Not sure how your file is formatted, but if it is in the form of:
Question
Answer
Question
Answer
.
.
.
Question N
Answer N
You can call enumerate()
over a generator within the context manager and go to specific lines. For example, if you know the line number or perhaps build a dictionary of Q&A for even lines:
with open(myfile, 'r') as f:
q_a = {}
for num, line in enumerate(line for line in f):
if num % 2 = 0:
question = line
else:
q_a[question] = line