代码之家  ›  专栏  ›  技术社区  ›  Taylor Johnson

Python打印文件行搜索的第一个实例

  •  0
  • Taylor Johnson  · 技术社区  · 3 年前

    我正在解析一个.desktop文件,它是python。我写了以下内容来查找要启动的应用程序的名称。

     ​                ​o2​ ​=​ ​self​.​name 
     ​                ​#create a temp file so that i can... 
     ​                ​tmp​ ​=​ ​tempfile​.​NamedTemporaryFile​() 
     ​                ​with​ ​open​(​tmp​.​name​, ​'w'​) ​as​ ​f​: 
     ​                        ​f​.​write​(​o2​) 
     ​                ​#use readline for a grep like function 
     ​                ​with​ ​open​(​tmp​.​name​) ​as​ ​f​: 
     ​                        ​for​ ​line​ ​in​ ​f​.​readlines​(): 
     ​                                ​if​ ​'Name='​ ​in​ ​line​:
    

     
     ​Name​=Alacritty 
     ​GenericName​=Terminal 
     ​Comment​=A fast, cross-platform, OpenGL terminal emulator 
     ​StartupWMClass​=Alacritty 
     ​Actions​=New; 
      
     ​[Desktop Action New] 
     ​Name​=New Terminal 
     ​Exec​=alacritty
    

    我想让它打印出第一个名字=你看到了,但它打印出了[Desktop Action New]下的最后一个名字。我如何解决这个问题?

    1 回复  |  直到 3 年前
        1
  •  0
  •   Brooke Jackson    3 年前

    所以你想打印第一个 'Name=' 但不是第二个? 如果这是您正在尝试做的,只需在打印第一个后中断循环即可

     ​                ​o2​ ​=​ ​self​.​name 
     ​                ​#create a temp file so that i can... 
     ​                ​tmp​ ​=​ ​tempfile​.​NamedTemporaryFile​() 
     ​                ​with​ ​open​(​tmp​.​name​, ​'w'​) ​as​ ​f​: 
     ​                        ​f​.​write​(​o2​) 
     ​                ​#use readline for a grep like function 
                     last_line = None
     ​                ​with​ ​open​(​tmp​.​name​) ​as​ ​f​: 
     ​                        ​for​ ​line​ ​in​ ​f​.​readlines​(): 
     ​                                ​if​ ​'Name='​ ​in​ ​line​:
                                             print(line)
                                             #maybe do some more staff, then :
                                             break
    

    '姓名=' 从被打印出来。