Home > Blockchain >  Python print first instance of a file line search
Python print first instance of a file line search

Time:12-02

I am parsing a .desktop file is python. I wrote the following to find the name of a app to launch.

 ​                ​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​:

Note: self.name is a string version of the. Desktop file.. The thing is every time I do the search it finds the last item in a search, I'll use alacritty as an example.

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

I want it to print out the first Name= you see but it prints out the last one under [Desktop Action New] how can I fix this?

CodePudding user response:

So you want to print the first 'Name=' but not the second one ? If it is what you are trying to do, just break the loop after printing the first '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

That will prevent the second 'Name=' from being printed.

  • Related