【问题标题】:Find string in a file and print which line it was found on [closed]Python:在文件中查找字符串并打印在[关闭]上找到的行
【发布时间】:2014-02-16 21:23:01
【问题描述】:

我多年来一直在浏览堆栈溢出问题,但找不到解决方案。我需要在 txt 文件中找到一个字符串,然后打印在哪一行找到了该字符串。作为白痴,我自己无法弄清楚这一点,也无法在这里找到答案。 因此,我需要一个可以做到这一点的 sn-p。 我正在使用 Python 2.7。

【问题讨论】:

  • 你试过什么?顺便说一句,这可以通过grep 完成,因此在您的情况下可能不需要编写新程序。
  • grep 如果在 Unix 中;否则,我会发现很难做到 =)

标签: python string file python-2.7 io


【解决方案1】:

在 Python 中,enumerate 对这类事情很方便:

with open(myfile) as f:
    for index, line in enumerate(f, 1):
        if s in line:
            print("'{0}' found on line {1}".format(s, index))

【讨论】:

  • 是的,s 是目标字符串。
  • 呸,堆栈溢出仍然是新手,并删除了我的评论。但是我制作了使其与 2.7 一起工作所需的模块,并且它完全按照我需要的方式工作。谢谢!
猜你喜欢
  • 2021-07-20
  • 1970-01-01
  • 2014-07-10
  • 2012-08-10
  • 2012-01-21
  • 1970-01-01
  • 2016-05-07
  • 2013-12-20
  • 1970-01-01
相关资源
最近更新 更多