在python中如何将特定行存储在变量中?

在python中如何将特定行存储在变量中?,python,linux,python-2.7,python-3.x,debian,Python,Linux,Python 2.7,Python 3.x,Debian,我有以下代码: with open("/etc/network/interfaces", "r") as file: content = file.read() print content 它正在发挥作用,并显示了这一点: 如何在变量中存储任何单词并打印该单词 with open("/etc/network/interfaces", "r") as file: for line in file: words=line.split(' ')#break the line

我有以下代码:

with open("/etc/network/interfaces", "r") as file:
    content = file.read()
    print content
它正在发挥作用,并显示了这一点:

如何在变量中存储任何单词并打印该单词

with open("/etc/network/interfaces", "r") as file:
for line in file:
    words=line.split(' ')#break the line into a list of words.
    print(words[0],words[1]) #
我没有测试过它,但给了你一个想法


例如,我想将单词lo存储在变量的第二行,然后打印该变量

使用Python内置库中的re模块:

import re

with open("/etc/network/interfaces", "r") as file:
    content = file.readlines()

target_word = re.findall("lo()", content[3]) # save the string 'lo' into target word
print ''.join(target_word) # prints: lo

如果打算查找更多单词,只需向正则表达式中添加更多单词即可。例如,如果你想找到单词lo和auto,你可以说re.findallo | auto,content。如果您使用此方法,我建议您阅读。

您到底在问什么?您想做什么?例如,我想将单词lo存储在变量的第二行,然后打印该变量。因此,对文件进行一些分析,然后。。。就一行还是。。。?目前这有点宽泛…你想对文件中的所有单词或只对给定数量的单词执行此操作?只对给定数量的单词执行此操作,例如,我有:lo在单词auto旁边看到了吗?我想在变量中保存该行中的单词lo,然后打印它。你能帮我吗?谢谢!为什么要打印四次?我怎样才能把lo保存到一个变量中?@AlvaroEnrique我可能误解了你。您想要所有出现的lo字,还是只想要lo字自动?是的,只想要lo字自动auto@AlvaroEnrique抓住你了。给我一点时间更新我的答案。