Skip to main content
 首页 » 编程设计

python之在文件中匹配字符串后处理文件

2025年01月19日28zhenyulu

我有一个正在处理的 json 文件,我不得不暂停操作,我想在我离开的地方再次开始处理,这是我正在使用的代码,问题是 If 条件甚至仍然执行如果不满足 While 循环条件,根据我的理解,代码应该无法访问,直到 While 循环不满足它的条件。我哪里错了?

row_counter = 0 
start_now = 0 
Finished = 0 
with open('jsonfile') as f: 
    for row in f: 
        row_counter += 1 
        if row_counter > start_now: 
            try: 
                row = json.loads(row) 
                comment_id = row['id'] 
 
                while Finished == 0: 
                    if (comment_id != 'The_String_I_Wanna_Match'): 
                        Finished = True 
                        break 
 
                if (condition): 
                    print('code i want to execute') 
            except Exception as e: 
                print(e) 
        if (row_counter % 100000 == 0): 
            print('no. of rows gone by {}'.format(row_counter)) 

请您参考如下方法:

所以我不太确定您在这里尝试做什么,因为您发布的大部分是伪代码,但您绝对不想使用 while 循环。如果第一行恰好与您要永远寻找的字符串匹配,则那里的 while 循环将锁定您的程序(除非您正在运行多线程,但您似乎不是)。我还认为您在那里使用了错误的条件运算符,但正如我所说,不能 100% 确定您在这里要做什么。

这就是我认为您需要的:

import json 
 
row_counter = 0 
start_now = 0 
 
with open('file.json') as f: 
  for row in f: 
    row_counter += 1 
    if row_counter > start_now: 
      try: 
        # check to ensure we're not messing with a blank row 
        if not row: continue 
 
        # load the row. This line might throw an exception if the  
        # line isn't perfect json 
        row = json.loads(row) 
        print(row) 
        comment_id = row['id'] 
 
        if(comment_id == 'The_String_I_Wanna_Match'): 
          print('Execute code here') 
 
      except Exception as e: 
        import traceback 
        print(traceback.print_exc()) 
    if (row_counter % 100000 == 0): 
      print('no. of rows gone by {}'.format(row_counter))