0

I have a huge text file similar to the table in below link. Each xxx box has different number of lines but same number of column:

Here is the link to figure

  • First point in the figure is the average of the first 3 values in the table,

  • Second is the average of the first 5 values,

  • Third is the average of first 8 values,

  • and so on ...

I could not write a general python code which works for whole text file. Could you please help me about that?

I tried this code but I got error:

1 Answers1

0

I believe the general layout of what you are looking for is:

with open('file','r') as file:
    groups = [] # Will contain the final data
    current_group = [] # Temporary

    line = file.readline()
    while line != "":
        if line == "XXXX":
            # Store the current group and start a new one
            groups.append(current_group)
            current_group = []
        else:
            # Add the number to the current group
            current_group.append(int(line.split()[2]))
        line = file.readline()
Marc J
  • 1,303
  • 11
  • 11
  • current_group.append(int(line.split()[2])) : IndexError: list index out of range – Alireza Bahrami Apr 14 '16 at 06:38
  • @AlirezaBahrami It means that there are less than 3 items (separated by spaces) on the line. You need to modify that line to do whatever data parsing is appropriate. I cant help you because I dont know the specifics of the input file. – Marc J Apr 14 '16 at 17:26
  • Also, I was just trying to show how you would iterate through the lines adding to a group, and then start a new group each time a boundary is crossed. – Marc J Apr 14 '16 at 17:27