AttributeError:'str'对象在尝试比较两个字符串变量时没有属性'readline'

时间:2015-02-18 14:34:26

标签: python attributeerror

我正在尝试计算一个顶级域实例的数量,该文件包含我从URL中删除的包含800K +顶级域字符串的文件。在下面的代码中,当我使用“if mstlds in ntld:”时,结果似乎是正确的但在检查时“co”和“com”,“ca”和“cat”计数是不正确的。但是,如果我使用==或“是”,我根本不会得到任何匹配,而是一个错误:

追踪(最近一次通话):   文件“checktlds4malware.py”,第111行,in     mtlds_line = mtlds.readline() AttributeError:'str'对象没有属性'readline'

tld_file = open(sys.argv[1],'r')
tld_line = tld_file.readline()
while tld_line:
    #print(tld_line)
    tld_line = tld_line.strip()
    columns = tld_line.split()
    ntld = columns[0]           # get the ICANN TLD
    ntld = ntld.lower()

    mtlds = open ('malwaretlds.txt', 'r')
    mtlds_line = mtlds.readline()
    while mtlds_line:
       print(mtlds_line)
       mtlds_line = mtlds_line.strip()
       columns = mtlds_line.split()
       mtlds = columns[0]
       mtlds = mtlds.lower()
       #raw_input()
       # I don't get the error when using "in" not ==
       # but the comparison is not correct.
       if mtlds_line == ntld:     
          m_count += 1
          print 'ntld and mtld match: Malware domain count for ', ntld, m_count
       mtlds_line = mtlds.readline()
    print 'Final malware domain count for ', ntld, m_count

1 个答案:

答案 0 :(得分:0)

这是因为在while循环中,您将mtlds设置为String。因此,一旦您尝试使用readline()方法,就会抛出错误(非常自我解释)。您必须记住,仅在内部while循环范围之外的mtlds指向文件。