Ad

I Need To Split A Seismological File So That I Have Multiple Subfiles

- 1 answer

Basically what I have is an ASCII file containing seismological information of various earthquake events. Each event (with its specific info) is separated from the following by a jumpline.

What I want is to split this huge file using python into a series of subfiles that contain approximately 700 events each with its own information, and these subfiles must be chronologically organized.

The original file look like this:

Screenshot

You can see that between the first and second event is a jumpline and so every following events.

Thanks in advance for your help

Ad

Answer

In principle you can do like that:

inputFile = "AllEvents.txt"               # give the path to the file that contain all the events
eventInfo = ""                            # create a string to hold event info
eventCounter = 0
fileId = 0

subFile= open("Events" + str(fileId) + ".txt","w+")          # create the sub file that you need

with open(inputFile) as fileContent:
    for line in fileContent:
        if not line.strip():              # strip white spaces to be sure is an empty line
            subFile.write(eventInfo + "\n")      # add event to the subFile
            eventInfo = ""                # reinit event info
            eventCounter += 1
            if eventCounter == 700:
                subFile.close()
                fileId += 1
                subFile = open("Events" + str(fileId) + ".txt","w+")
                eventCounter = 0
        else:
            eventInfo += line
subFile.close()

At the end you will have a list of files, each with 700 events: Events0.txt, Events1.txt, ...

Ad
source: stackoverflow.com
Ad