Skip to main content
 首页 » 编程设计

python之在 Python 中,如何从 txt 文件中读取未知数量的行

2025年05月04日16zhoujg

这是用例。我有一个可能有数十万行的文本文件,其中: 第一行包含整数 N,这是后续行的数量。我知道如何读取第一行并将其转换为 int;但是,我已经搜索了一种方法来从文件中读取该行数但没有成功。

例如: 输入.txt

4 
foo 
bar 
carrot 
snowflake 

我将读取这些行并将其存储在变量中。没有空行。

如何从我的文本文件中获取接下来的 N 行,最好以 Pythonic 方式?

请您参考如下方法:

您可以使用 itertools.islice , 获取 n 使用 next 获取第一行,然后将 n 传递给 islice 以获取下一个 n 行:

from itertools import islice 
 
with open("in.txt") as f: 
    n = int(next(f)) 
    lines = list(islice(f, n)) 

您也可以只遍历 islice 对象:

with open("in.txt") as f: 
    n = int(next(f)) 
    for line in islice(f,n): 
        print(line)