Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python print first instance of a file line search

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading