2017-01-09 18 views
-2

私は次の形式で注文情報を格納するテキストファイルを持っています。私はブロックの最初の行でIDを表し、次の7行を印刷して注文を検索しようとします。しかし、私のコードは最初の行だけをチェックしたり、入力番号を含むすべての行を出力したりします。誰かが私を助けることができますか?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

なぜファイルを2回開いたのですか?最初のオープンは不要です。代わりにロジックを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つのタスクに対して2回ファイルを開く必要はありません。 –

答えて

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を入力した後にプログラムを閉じるだけですが、if if idline.startswith( "["):print idline else :break'プログラムはブロックを見つける総額を表示し、実際にうまくいきます。しかし、次の6行を表示する方法を見つける必要があります) –

関連する問題