我有文本文件,以下列格式存儲訂單信息。我嘗試在塊的第一行搜索訂單,這表示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()
爲什麼你打開文件兩次,第一次打開是不必要的,而不是在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子句。但是爲單個任務打開文件兩次是不必要的。 –