私は次の形式で注文情報を格納するテキストファイルを持っています。私はブロックの最初の行で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()
なぜファイルを2回開いたのですか?最初のオープンは不要です。代わりにロジックをtryブロックに含めてください。 –
'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
彼は引き続きexcept節を使用することができます。 1つのタスクに対して2回ファイルを開く必要はありません。 –