2017-01-09 50 views
-2

我有文本文件,以下列格式存儲訂單信息。我嘗試在塊的第一行搜索訂單,這表示ID並打印下一行。但我的代碼只檢查第一行或打印包含輸入數字的所有行。有人能幫助我嗎?Python:在文件中搜索特定的字符串

4735 
['Total price: ', 1425.0] 
['Type of menu: ', 'BBQ'] 
['Type of service: ', '  '] 
['Amount of customers: ', 25.0] 
['Discount: ', '5%', '= RM', 75.0] 
['Time: ', '2017-01-08 21:39:19'] 

3647 
['Total price: ', 2000.0] 
['Type of menu: ', ' '] 
['Type of service: ', 'Tent '] 
['Amount of customers: ', 0] 
    ....... 

我使用下面的代碼在文本文件中搜索。

 try: 
      f = open('Bills.txt', 'r') 
      f.close() 
     except IOError: 
      absent_input = (raw_input("|----File was not founded----|\n|----Press 'Enter' to continue...----|\n")) 
      report_module = ReportModule() 
      report_module.show_report() 
     Id_input = (raw_input("Enter ID of order\n")) 
     with open("Bills.txt", "r") as f: 
      searchlines = f.readlines() 
     j = len(searchlines) - 1 
     for i, line in enumerate(searchlines): 
      if Id_input in str(line): # I also try to check in this way (Id_input == str(line)), but it didn't work 
       k = min(i + 7, j) 
       for l in searchlines[i:k]: print l, 
       print 
      else: 
       absent_input = (raw_input("|----Order was not founded----|\n|----Press 'Enter' to continue...----|\n")) 
       report_module = ReportModule() 
       report_module.show_report() 
+1

爲什麼你打開文件兩次,第一次打開是不必要的,而不是在try塊中包含你的邏輯。 –

+1

正如你在'except'塊中看到的那樣,他檢查文件是否存在。 @Bogdan:使用https://docs.python.org/2/library/os.path.html#os.path.exists或https://docs.python.org/2/library/os.path.html# os.path.isfile更清潔 – BloodyD

+1

他仍然可以使用except子句。但是爲單個任務打開文件兩次是不必要的。 –

回答

1

請檢查以下代碼。

Id_input = (raw_input("Enter ID of order\n")).strip() 
try: 
    f = open("Bills.txt", "r") 
    print_rows = False 
    for idline in f: 
     if idline.strip() == Id_input: 
      print_rows = True 
      continue 
     if print_rows: 
      if idline.startswith("["): 
       print idline 
      else: 
       break 

    if not print_rows: 
     absent_input = (raw_input("|----Order was not founded----|\n|---- Press 'Enter' to continue...----|\n")) 
     report_module = ReportModule() 
     report_module.show_report() 
except IOError: 
     absent_input = (raw_input("|----File was not founded----|\n|---- Press 'Enter' to continue...----|\n")) 
     report_module = ReportModule() 
     report_module.show_report() 
+0

我得到一個錯誤,'AttributeError:'str'對象沒有'stripe''屬性 –

+0

我的壞,錯字!再次檢查,str.strip()條紋任何白色空間,這樣就很容易比較 –

+0

嗯,這段代碼不起作用,只要在輸入ID後關閉程序,但是如果刪除'else' if ifline.startswith(「[」):print idline else :break'程序將顯示查找塊的總價格,它實際上運行良好。但需要找到一種方法來顯示下6行) –