简体   繁体   English

如何读取 Python 3 中输入文件的特定部分?

[英]How to read specific parts of a input file in Python 3?

Let's say I have an input file with the following data:假设我有一个包含以下数据的输入文件:

50 50
A
B
C
D

I know that I can extract the first line using the map function as follow:我知道我可以使用 map function 提取第一行,如下所示:

x,y= map(int, input().split())

But I am unsure how I can retrieve the next 4 lines and put them into a list.但我不确定如何检索接下来的 4 行并将它们放入列表中。 I tried using the splitlines() function, since each value is on a seperate line, but that only returns the first value.我尝试使用 splitlines() function,因为每个值都在单独的行上,但只返回第一个值。

strings = input().splitlines()

How can I choose what parts of the input file I want to read and then store them in respective variables?如何选择要读取的输入文件的哪些部分,然后将它们存储在相应的变量中?

Open the file, read all the lines into a list, do what you want with them打开文件,将所有行读入列表,对它们做你想做的事

with open("[filename]", "r") as f:
    lines = list(map(lambda l: l.strip(), f.readlines()))

# do whatever with the lines here
# use lines.pop(0) if you want to remove the line from the list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM