给定行号,如何从文件中读取它

时间:2018-01-03 13:19:00

标签: python python-3.x

继承我的代码:

borders.addNewBottom().setVal(STBorder.THICK);

每当我输入任何数字时,它总是打印相同的行。

2 个答案:

答案 0 :(得分:3)

Python有一个方便的linecache库来处理你的情况:

import linecache

def option_a():
    line_number = int(input("Enter a line number: "))
    line = linecache.getline("firesideFixtures.txt", line_number)
    print(line)

答案 1 :(得分:1)

readlines()的参数没有指定从文件中读取哪一行。尝试这样的事情:

def option_a():
    fixchoice = int(input("Enter: "))

    with open("firesideFixtures.txt", "r") as file:
        for i, line in enumerate(file, 1):
            if i == fixchoice:
                print(line)
                break # Or return if you don't want to do anything after the loop

option_a()