从文本文件中分别读取和打印?

时间:2016-11-02 19:09:23

标签: python

所以下面我的代码必须从文件中读取以打印文件的内容。我的问题是如何单独打印文件中的行,以便它们不是一次打印,而是仅在需要时打印?

input = input('Type:')

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

        text_file.close()

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

        text_file.close()

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

        text_file.close()

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

        text_file.close()

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

        text_file.close()

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

        text_file.close()

先谢谢你的帮助:)

3 个答案:

答案 0 :(得分:0)

如果您知道所需响应的行号并且文本文件不是那么大,您可以将文件行读入列表。

text_file = open("task2_solutions.txt", "r")
responses = text_file.read().split("\n")
text_file.close()

然后,您可以通过索引列表中的已知行号来访问相应的响应:

if user_input == ('wifi'):
    print(response[0])

答案 1 :(得分:0)

我认为您最初可以读取此文件中的所有行,然后使用正则表达式根据字典中的关键字分隔这些行。之后,您可以使用字典来获得所需内容。

答案 2 :(得分:0)

您可以使用如下例所示的字典。优点是您可以使用一系列行号,它还可以简化代码:

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]:
        print line
相关问题