期望一个字符缓冲区对象:Python 2.7

时间:2014-11-21 17:28:09

标签: python python-2.7

我试图从文本文件中获取一行的第三个元素,但在尝试时我得到了上面提到的错误。以下是我的代码

def time_difference():
    button_pressed = ''
    command = ''
    b_p_c_s = ''
    next_line_to_command = ''
    test = ''
    print "\n\033[32m-- TIME DIFFERENCES --\033[0m\n"
    with open('messages', 'r') as searchfile:
        for line in searchfile:
            if ':Button' and 'pressed' in line:
                button_pressed = str(line)
                with open('buttonpress_and_commandstarted','a') as buttonpressed:
                    buttonpressed.write(button_pressed)
                buttonpressed.close()
            elif 'Command' and 'started' in line:
                command = str(line)
                with open('buttonpress_and_commandstarted','a') as commandstarted:
                    commandstarted.write(command)
                buttonpressed.close()
        with open('buttonpress_and_commandstarted','a') as file_opened:
            file_opened.close()
        with open('buttonpress_and_commandstarted','r') as buttonpress_commandstarted:
            b_p_c_s = buttonpress_commandstarted.read()
            print b_p_c_s
        buttonpress_commandstarted.close()
        print "\n\033[32m-- NEXT TO KEYWORDS --\033[0m\n"
        with open('buttonpress_and_commandstarted', 'r') as searchfile:
            for line in searchfile:
                try:
                    if 'Command' and 'started' in line:
                        next_line_to_command = searchfile.next()
                        test = str(next_line_to_command)
                        print next_line_to_command
                except StopIteration:
                    pass
            print "\n\033[32m-- TIME --\033[0m\n"
            test.split(3) 
        searchfile.close()

我得到了

Traceback (most recent call last):
  File "./gui-analyser.py", line 114, in <module>
    time_difference()
  File "./gui-analyser.py", line 106, in time_difference
    test.split(3) 
TypeError: expected a character buffer object

我的目的是获取行中空格后的第三个元素,例如

Jan 01 07:24:07 AMIRA-134500021 user.notice butler[775]: LOG:200708a0:12:Button 11 pressed.

在这种情况下 07:24:07

我看到了一些论坛,因为只能使用字符串进行拆分,所以我将变量转换为字符串但我得到了这个问题。任何指导都会非常有用。

1 个答案:

答案 0 :(得分:2)

str.split()作为第一个参数,用于分割输入字符串的字符串。你试图将它传递给整数。

如果你想拆分空格并从结果中挑出一个特定的元素,那么索引返回的列表:

third_element = test.split()[2]

其中Python使用基于0的索引,因此使用2作为索引来访问第三个元素。请注意,这会返回值,因此您可能希望存储该结果。