简体   繁体   中英

Python Parse lines of input file

Im a recent graduate who has made some contacts and trying to help one with a project. This project will help evolve into something open source for people. So any help I can get would be greatly appreciated.

Im trying to parse out certain items in a file I have succeeded in parsing out the specific items. I now need to figure out how to attach all the remaining data to another variable in an organized way for example.

file=open("file.txt",'r') 

row = file.readlines()

for line in row:
    if line.find("Example") > -1:
        info = line.split()
        var1 = info[0]
        var2 = info[1]
        var3 = info[2]
        remaining_data = ????

^^^^^^^^^^is my sample code already doing 90% of what i need. I want to get the remaining_data to all go into that variable line by line for.

print remaining_data

output:remaining_data{
    line 1 of data
    line 2 of data
    line 3 of data
    line 4 of data
}

how can I get it organized and going in like that line by line?

remaining_data = []
for line in open("file.txt",'r'):
    if line.find("Example") > -1:
        info = line.split()
        var1 = info[0]
        var2 = info[1]
        var3 = info[2]
        remaining_data.append(' '.join(info[3:]))

at the end of the loop, remaining data will have all lines with out the first 3 elements

by using a slice

remaining_data=info[3:]

If you need the indices you could do

for i, line in enumerate(info[3:]):
    print("{}: {}".format(i, line))

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