Python:在行文件中查找字符串,空输出

时间:2016-02-22 17:14:29

标签: python line

我搜索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

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您在for循环中重复input_f而不是input_data:)

答案 1 :(得分:1)

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

使用input_data时可能无效,因为您的行中没有标签或任何以ABC开头的行;无法看到输入,这是不可能的。

答案 2 :(得分:1)

如果你想要的是让你的文件中的第一行以' 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(带文件路径的字符串)。