简体   繁体   中英

Search a line in text file and write a word before it

I am trying to parse a text file search for functions and add i to that line. My input file is a text file where the data is column format. I read this text file search for all functions with arguments and add an extra column which has i written to every row that has the functions with arguments and v written to every row that has functions without arguments. The logic I used is

filter_list = ["int","unsigned","void","*"]
for line in f:
    if ".text" in line:
         if "()" in line:
            columns = line.split("  ")
            columns.insert(0, "v")
            g.write("  ".join(columns)+"  ")
            continue

         if "(" in line:
            for word in filter_list:
                columns = line.split()
                columns.insert(0, "i")
                g.write("  ".join(columns)+"  ")




f.close()
g.close()

This does not give the right output. This logic keeps on adding i to complete row after the first argument like

i  00010518  .text  hl_mount_storage(FileSystemObject&,  char  i  00010518  .text  hl_mount_storage(FileSystemObject&,  char  i  00010518  .text  hl_mount_storage(FileSystemObject&,  char  i  00010518  .text  hl_mount_storage(FileSystemObject&,  char  a  2007c000  .data  g_pkt_hist_wptr

This line repeats the g.write to the output file for each of the words in your filter:

for word in filter_list:

so currently, 4 times (the length of filter_list ). If you add another word, you'd get 5 copies of the same line.

Since you don't use word or filter_list anyway, just remove the entire for loop:

if "(" in line:
    columns = line.split()
    columns.insert(0, "i")
    g.write("  ".join(columns)+"  ")

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