从文本文件中读取某一行,并只打印该行的一部分。

问题描述 投票:-2回答:3

我有一个文本文件,看起来像这样。

test=HelloWorld
test=
test2=blabla

我怎么能只打印后面的内容 test=? 谢谢!我有一个文本文件是这样的:test=HelloWorld test= test2=blabla 如何才能只打印test=后面的内容?

python python-3.x
3个回答
-1
投票

这能解决你的问题吗?

txt = """
test=HelloWorld
test=
test2=blabla"""

for line in txt.split('\n'):
    split = line.split('=')
    if split[0] == 'test':
        print(split[1])

字符串的例子,当然,你需要正确加载你的文件。

你可以用split()拆分特定字符的字符串,返回一个列表。


0
投票

你需要使用regex来查找text=后面的内容,比如:".*=(.*)"。 ".*=(.*)

然后抓住match1中的内容。

参见这里了解如何在 Python 中使用 regex。

https:/docs.python.org3howtoregex.html#grouping


0
投票

运行这个(资料来源):

for line in open("filename.txt"):
 if "o" in line:
  print(line)

它只会显示出带有字母 "o "的行。如果你想删除 test= (资料来源):

for line in open("palc.log"):
 if "o" in line:
  print(line.replace("test=", ""))

我希望这能帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.