我搜索以便找到带有特定字符串的输入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
谢谢你的帮助。你知道吗
您在for循环中迭代的是
input_f
,而不是input_data
:)如果要获取文件中以“ABC\t”开头的第一行,则更简单、更有效和更具python风格的方法是:
如其他人所说,您需要输入\ u数据(文件描述符),而不是输入\ f(带有文件路径的字符串)。你知道吗
input_f
是文件的路径;input_data
是关联的文件对象,这就是for
循环应该使用的对象。你知道吗也许当你使用
input_data
时它不起作用,因为你的行中没有制表符,或者任何以ABC
开头的行;看不到输入,这是不可能的。你知道吗相关问题 更多 >
编程相关推荐