Lopin Lopin - 1 month ago 14
Python Question

Reading and printing from a text file in separate lines?

So below I have my code for a mobile phone troubleshooting system which has to help a user find out their issue with their phone. My code has to read from a file to print the solutions to their issue. My question is how would I print the lines in the file separately so they don't all print at once but only if they are needed?

user_input = input('Welcome to the troubleshooting system, please state which category you have having issues with:')

if user_input == ('wifi'):
text_file = open("task2_solutions.txt", "r")
print (text_file.read(39))

text_file.close()

elif user_input == ('storage'):
text_file = open("task2_solutions.txt", "r")
print (text_file.read(39))

text_file.close()

elif user_input == ('power'):
text_file = open("task2_solutions.txt", "r")
print (text_file.read(39))

text_file.close()

elif user_input == ('screen'):
text_file = open("task2_solutions.txt", "r")
print (text_file.read(39))

text_file.close()

elif user_input == ('texts'):
text_file = open("task2_solutions.txt", "r")
print (text_file.read(39))

text_file.close()

elif user_input == ('calls'):
text_file = open("task2_solutions.txt", "r")
print (text_file.read(39))

text_file.close()

else:
print("Sorry but that issue is either not in our database or you have not inputted your answer correctly. (Eg. please state which category you have having issues with: wifi")


Here is a screenshot of the text file i'm trying to print separately when needed.

Thanks in advance for your help :)

Answer

You can use a dictionary as shown in the example below. The advantage is that you can use a range of line numbers and it will also simplify the code:

import fileinput

plines = {'wifi':[1],'storage':[4]}
user_input = input('Welcome to the troubleshooting system, please state which category you have having issues with:')

for line in fileinput.input("task2_solutions.txt"):
    if fileinput.lineno() == plines[user_input][0]:
        print line
Comments