gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:22 25 4
gpt4 key购买 nike

这是用例。我有一个可能有数十万行的文本文件,其中:第一行包含整数 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)

关于python - 在 Python 中,如何从 txt 文件中读取未知数量的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32222216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com