Python:在文件中搜索特定字符串

时间:2017-01-09 08:00:26

标签: python file search

我有文本文件,以下列格式存储订单信息。我尝试通过块的第一行搜索一个订单,它代表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()

1 个答案:

答案 0 :(得分: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()