简体   繁体   中英

Extract a particular word at a particular position in a line using Python

I have a set of lines in a file like below.

mov 66 (56.9%) 5406720 (56.9%)

I want to identify these lines in a set of files and extract the first (mov) and fifth field (5406720 in the above case) and write this to a separate single file.

Thanks & regard, santosh

It's easy. First open your file and read each line

With open(file name, ‘r’) as f:
    Line = f.readline()
    Data = Line.split(“ “)
    If “mov” is Data[0]:
        Nf = open(new file,’w’)
        Nf.write(Data[0]+” “+Data[4]
        Nf.close()

This will open your text file. Read each line and look for lines starting with “mov” and if so create and write a new file with “mov” and your fifth field.

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