【发布时间】:2017-01-09 08:00:26
【问题描述】:
我有文本文件,以以下格式存储订单信息。我尝试按块的第一行搜索订单,代表 ID 并打印下 7 行。但是我的代码只检查第一行或打印所有包含输入数字的行。有人可以帮帮我吗?
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:使用docs.python.org/2/library/os.path.html#os.path.exists 或docs.python.org/2/library/os.path.html#os.path.isfile 更干净 -
他仍然可以使用 except 子句。但是没有必要为单个任务打开文件两次。
-
最近,我因为 catching exceptions is more Pythonic 建议进行简单检查而不是让 Python 崩溃和烧毁而受到谴责。我们能否请您对此做出决定:P