在Python中阅读几行

时间:2018-09-26 08:28:27

标签: python file

我目前遇到一个问题,我需要从文本文件中读取N行, 一共有50行,但我想让用户选择要选择的行数。

我不知道从哪里开始。

3 个答案:

答案 0 :(得分:2)

尝试一下:

user_demand = int(input('how many lines?'))
if user_demand > 50:
    user_demand = 50

with open('filename.txt', 'rb') as file:
    for i, line in enumerate(file):
        if i == user_demand:
            break
        print(line)

答案 1 :(得分:1)

首先,您需要打开文件:

txt = open(r"yourfile.txt","r")

现在您可以阅读它。

lines = 0
for line in txt:
    if lines >= max_lines: break #max_lines is the input by the user
    #do something
    lines = lines + 1
txt.close()

或者您可以使用readline()将所有行存储在数组中,然后仅打印或使用用户想要的行数。

注意:此任务有很多更好,更有效的解决方案。这为您提供了一个“快速入门”:)

答案 2 :(得分:1)

您可以执行以下操作:

# open the file
file = open("filename.txt")
# load lines into a list
all_lines = file.readlines()

# get input
amount_lines = input("How many lines do you want to print? ")
# turn input (string) into an integer
amount_lines_int = int(amount_lines)

# do something with all the lines from index 0 to index amount_lines_int (excl.)
for line in all_lines[:amount_lines_int]: 
    # strip line frome whitespace (i.g. the paragraph)
    line = line.strip()
    print(line)

file.close()