【问题标题】:Python: find string in line file, empty outputPython:在行文件中查找字符串,空输出
【发布时间】:2016-02-22 17:14:29
【问题描述】:

我搜索了 SO 以找到带有特定字符串的输入 txt 文件的第 # 行。 How do I read the first line of a string? 但是我没有得到任何输出,它是空的。我使用以下python代码:

with open(input_f) as input_data:
    print input_f  # test if reading correct file: yes
    for line in input_f:  # originally  'in input_data': no output
        if line.split('\t', 1)[0] == 'ABC':  # string before tab
        #if line.startswith('ABC'):  ... also empty output
            print line  # nothing is printed

感谢您的帮助。

【问题讨论】:

  • 你需要遍历 input_data,而不是 input_f。
  • 向我们展示输入文件。
  • 您正在迭代 input_f,它是文件的路径,而不是 input_data,它是文件对象
  • 你应该详细说明,不清楚你在问什么。

标签: python line


【解决方案1】:

您在 for 循环中迭代 input_f 而不是 input_data :)

【讨论】:

    【解决方案2】:

    input_f是文件的路径; input_data 是关联的文件对象,这是 for 循环应该使用的。

    也许当您使用input_data 时它不起作用,因为您的行中没有制表符,或者任何以ABC 开头的行;看不到输入,没法说。

    【讨论】:

      【解决方案3】:

      如果您想要获取文件中以 'ABC\t' 开头的第一行,那么更简单、更高效且更 Pythonic 的方法是:

      with open(input_f) as input_data:
          your_value = next(line for line in input_data if line.startswith('ABC\t'))
      

      正如其他人所说,您需要遍历 input_data(文件描述符),而不是 input_f(带有文件路径的字符串)。

      【讨论】:

        猜你喜欢
        • 2017-11-30
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多