我需要分割一个地震文件,这样我就有多个子文件

2024-05-16 23:46:19 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我有一个ASCII文件,包含各种地震事件的地震学信息。每个事件(及其特定信息)通过一条跳线与下列事件分开。你知道吗

我想要的是使用python将这个巨大的文件分割成一系列子文件,这些子文件包含大约700个事件,每个事件都有自己的信息,这些子文件必须按时间顺序组织。你知道吗

原始文件如下所示:

Screenshot

你可以看到第一个和第二个事件之间是一条跳线,所以接下来的每个事件。你知道吗

提前谢谢你的帮助


Tags: 文件信息顺序ascii时间事件地震学地震
1条回答
网友
1楼 · 发布于 2024-05-16 23:46:19

原则上你可以这样做:

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()

最后你会有一个文件列表,每个文件有700个事件:Events0.txt,Events1.txt。。。你知道吗

相关问题 更多 >