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

2024-04-25 19:36:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我搜索以便找到带有特定字符串的输入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

谢谢你的帮助。你知道吗


Tags: 文件字符串intxtreadinputoutputdata
3条回答

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

如果要获取文件中以“ABC\t”开头的第一行,则更简单、更有效和更具python风格的方法是:

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

如其他人所说,您需要输入\ u数据(文件描述符),而不是输入\ f(带有文件路径的字符串)。你知道吗

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

也许当你使用input_data时它不起作用,因为你的行中没有制表符,或者任何以ABC开头的行;看不到输入,这是不可能的。你知道吗

相关问题 更多 >