Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python3中读取输入文件的特定部分?_Python_Python 3.x - Fatal编程技术网

如何在Python3中读取输入文件的特定部分?

如何在Python3中读取输入文件的特定部分?,python,python-3.x,Python,Python 3.x,假设我有一个包含以下数据的输入文件: 50 50 A B C D 我知道我可以使用map函数提取第一行,如下所示: x,y= map(int, input().split()) 但我不确定如何检索接下来的4行并将其放入列表中。我尝试使用splitlines()函数,因为每个值都位于单独的行上,但这只返回第一个值 strings = input().splitlines() 如何选择要读取的输入文件的哪些部分,然后将它们存储在相应的变量中?打开文件,将所有行读取到列表中,对它们执行所需操作

假设我有一个包含以下数据的输入文件:

50 50
A
B
C
D
我知道我可以使用map函数提取第一行,如下所示:

x,y= map(int, input().split())
但我不确定如何检索接下来的4行并将其放入列表中。我尝试使用splitlines()函数,因为每个值都位于单独的行上,但这只返回第一个值

strings = input().splitlines()

如何选择要读取的输入文件的哪些部分,然后将它们存储在相应的变量中?

打开文件,将所有行读取到列表中,对它们执行所需操作

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

input()
函数用于控制台输入,而不是文件。到目前为止您尝试了什么?有多个文件,每个文件都有一组不同的输入。我需要考虑所有这些文件,这就是为什么我不能指定文件名。