2017-09-16 52 views
-2
def main(): 
    found = False 
    coffee_file = ('c:/test/coffee.txt', 'r') 
    search = input("Enter a description to search :- ") 

    descr = coffee_file.readline() 

    while (descr != ''): 
     qty = (coffee_file.readline()) 
     descr = descr.rstrip('\n') 
     qty = qty.rstrip('\n') 

     if ('search' == descr): 
      print("Description :- ", descr) 
      print("Quantity :- ", qty) 
      print 

      found = True 

     descr = coffee_file.readline() 

    coffee_file.close() 


main() 

让我投掷AttributeError: 'tuple' object has no attribute 'readline'如何在Python中调试“AttributeError:'元组'对象没有属性'readline'”?

+0

这是我的文件看起来像其试图从下面的信息中读取数据: - 说明: - 印度咖啡 数量: - 10 说明: - 斯里兰卡咖啡 数量: - 11 描述: - 中国咖啡 数量: - 12 – Jijith

+0

我eror日志: - 输入说明搜索: - 印度咖啡 回溯(最近通话最后一个): 文件“C:/用户/ jimmyj /桌面/读取与loop.py文件“,第26行,在 main() 文件”C:/ Users/jimmyj/Desktop /使用for loop.py读取文件“,第7行,在主 descr = coffee_file.readline() AttributeError:'元组'对象没有属性'readline' >>> – Jijith

+0

您应该替代'coffee_file =('c:/test/coffee.txt','r' )''''coffee_file = open('c:/test/coffee.txt','r')''。另外,你应该在你的循环中加入'break'语句,或者在'coffee_file'中使用'for line'。 –

回答

0
  1. 您的错误发生在coffee_file=('c:/test/coffee.txt','r')行。你应该写coffee_file=open('c:/test/coffee.txt','r')。我使用with声明替换了由contex经理的那个。
  2. 你的while循环是无限的,所以我用for循环。
  3. 您正在比较字符串“search”和变量“descr”,该变量是文件的第一行。

假设你想找到的文件促进字符串 - 此代码应工作:

def main(): 
    found = False 
    search = input("Enter a description to search :- ").rstrip() 

    with open('c:/test/coffee.txt') as coffee_file: 
     for line in coffee_file: 
      qty = line.rstrip() 
      if search == qty: 
       print("Description :- ", search) 
       print("Quantity :- ", qty) 
       found = True 

    if not found: 
     print("Description :- ", search) 
     print("Quantity :- not found") 

main() 

附:请在下次提供您的输入数据(此例中为c:/test/coffee.txt)样本和预期输出。

+0

我的样品数据为: - + ++++++++++++++++++++ 描述: - 印度咖啡 数量: - 10 描述: - 斯里兰卡咖啡 产品数量: - 11 描述: - China Coffee 数量: - 12 描述: - 美国 数量: - 15 预期的O/P: 说明: - 数量: - – Jijith

+0

: - 你能帮助我.... – Jijith

+0

@Jijith我可以,但你可以编辑您的文章,而不是在发布数据的评论?如果没有适当的标准,很难猜测你的脚本应该如何工作 –

相关问题