首页 > 解决方案 > 使用来自另一个文件的值从一个文件中读取特定行

问题描述

我有两个文件。一个文件包含多行数字。另一个文件包含文本行。我想从数字列表中查找特定的文本行。目前我的代码看起来像这样。

a_file = open("numbers.txt")
b_file = open("keywords.txt")

for position, line in enumerate(b_file):
    lines_to_read = [a_file]
    if position in lines_to_read:
        print(line)

数字中的值看起来像这样..

26
13
122
234
41

关键字中的值看起来像(示例)

this is an apple
this is a pear
this is a banana 
this is a pineapple
...
...
...

我可以手动写出这样的值

lines_to_read = [26,13,122,234,41]

但这违背了使用 a_file 查找 b_file 中的值的意义。我尝试过使用字符串和其他变量,但似乎没有任何效果。

标签: pythonfileline

解决方案


[a_file]是一个包含一个元素的列表,即a_file. 您想要的是一个列表,其中包含您可以使用a_file.readlines()或获得的行list(read_lines)。但是您不想要行的文本值,而是它们的整数值,并且您希望经常搜索容器,这意味着集合会更好。最后,我会写:

lines_to_read = set(int(line) for line in a_file)

现在很好:

for position, line in enumerate(b_file):
    if position in lines_to_read:
        print(line)

推荐阅读