Use readlines
and output the lines according to their index
.
with open('addon/entertainment.txt') as f:
lines = f.readlines()
for line in lines:
print("{}. {}".format(lines.index(line) + 1, line))
desired_lines = [3, 5]
output = []
for desired in desired_lines:
output.append(lines[desired - 1])
for o in output:
print("{}. {}".format(output.index(o) + 1, o))
Alternatively, if you want to select lines based on an input
call, replaced desired_lines
with:
desired_lines = input().split(", ")
# can choose one number or multiple numbers like this: "3, 5"
output = []
for desired in desired_lines:
output.append(lines[int(desired) - 1])
for o in output:
print("{}. {}".format(output.index(o) + 1, o))
Note that if your input goes higher than number of lines in your text file, you’ll raise a IndexError
exception.
1
solved How to print word that you want inside a textfile?