简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM