Python 3如何使用文件中的读取线将特​​定行拉入数组

时间:2017-10-12 10:29:42

标签: python python-3.x

if diff_choice == ("1"):
    with open(topic_pull + ".txt", "r") as ins:
        questionarray = []
        for line in ins:
            line = line.strip()
            questionarray.append(line)

我怎么只将几条特定的线拉入数组(使用像readlines()这样的东西?)

提前致谢

P.S。文件看起来像这样:

问题

answ1

answ2

answ3

answ4

问题(等等) 如果用户想要“简单”的困难,它必须从文件中读取两个答案到数组中。我已经有了代码来确保答案不会重复到数组中。我想要的是readlines()函数从每个问题中读取随机答案并将其放入数组中。

2 个答案:

答案 0 :(得分:2)

更新回答

好的,这个问题被误解了。您要求根据您事先知道的索引提取不同的行。

当你打开一个文件时,你会得到一个迭代器。您可以读取变量的第一行,然后通过以下示例继续阅读下一行到另一行:

示例:

在示例中,我们在6行之后停止阅读。

string = """Question: Why?
Answer: Correct
Answer: Wrong 1
Answer: Wrong 2
Answer: Wrong 3
Question: Why?"""

with open("topic.txt","w") as f:
    f.write(string)

with open("topic.txt") as ins:
    # ins is now an iterator which you can extract info from
    question = ins.readline().strip() #Read first line
    answer = ins.readline().strip() #Read next
    wronganswers = [ins.readline().strip() for _ in range(3)] #Read next3
  

问题现在是一个字符串:'问题:为什么?'

     

回答现在是一个字符串:'答案:纠正'

     

wronganswers现在是一个列表:['...]

答案 1 :(得分:0)

如果您有包含所需行的列表,请尝试以下操作:

wanted_lines = [1, 3]

with open("foo.txt", "r") as ins:
    questionarray = [line.strip() for count, line in enumerate(ins.readlines()) if count in wanted_lines]

print(questionarray)

输出:

['line2', 'line3']

修改

您已接受我的回答,但这可以帮助找到想要的行:

question_lines = [0, 5, 10]
wanted_lines = []

mode = "easy"
wanted_lines += question_lines
for line in question_lines:
    if(mode == "easy"):
        wanted_lines.append(line+1)
    elif(mode == "normal"):
        wanted_lines.append(line+2)
    elif(mode == "hard"):
        wanted_lines.append(line+3)
    else: # very hard
        wanted_lines.append(line+4)


with open("foo.txt", "r") as ins:
    result = [line.strip() for count, line in enumerate(ins.readlines()) if count in wanted_lines]

print(result)

输出:

['Question1', 'answ1.1', 'Question2', 'answ2.1', 'Question3', 'answ3.1']