Samanradnia
Samanradnia

Reputation: 33

extract column of data from a text file using python

I want to extract a column of data from a text file.

The text file I have is as follows:( TOTAL TIME/FREQ is the column which i want to extract the numbers beneath that ! )

Abaqus/Standard 6.14-1                  DATE 07-Apr-2017 TIME 02:58:26
 SUMMARY OF JOB INFORMATION:
 STEP  INC ATT SEVERE EQUIL TOTAL  TOTAL      STEP       INC OF       DOF    IF
               DISCON ITERS ITERS  TIME/    TIME/LPF    TIME/LPF    MONITOR RIKS
               ITERS               FREQ
   1     1   1     3    10    13  0.0100     0.0100     0.01000   
   1     2   1U    1     4     5  0.0100     0.0100     0.01000   
   1     2   2     2     3     5  0.0125     0.0125     0.002500  
   1     3   1     1     4     5  0.0150     0.0150     0.002500  
   1     4   1     2     4     6  0.0188     0.0188     0.003750  
   1     5   1     2     5     7  0.0244     0.0244     0.005625  
   1     6   1     2     3     5  0.0300     0.0300     0.005625

Could you tell me how to write this code in python that could extract the numbers and then get the lists of numbers as follows?

[0.0100,0.0100,0.0125,0.0150,0.0188,0.0244,0.0300]

Upvotes: 1

Views: 645

Answers (1)

CodeCupboard
CodeCupboard

Reputation: 1585

This script should help. I have commented to state what each line does helping you adjust this for other scripts you want to create.

# A function to check if a value is an integer
def RepresentsInt(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False


#create empty output list
StepTimes = []

#open the text file
file1 = open('datFile.dat','r')

#read the text file line by line
for line in file1:

    #split file into a list
    line = line.split()
    #check if first item in list is an integer
    if RepresentsInt(line[0]):
        #append step time to a new list
        StepTimes.append(line[6])

print (StepTimes)

This returns

['0.0100', '0.0100', '0.0125', '0.0150', '0.0188', '0.0244', '0.0300']

Upvotes: 1

Related Questions