Search code examples
pythonsplitstrip

extracting data from a text file (python)


i have two columns of numbers in a text file which is the columns of time and stress respectively which i get it from an analysis in abaqus finite element package ! i want to extract the time column and stress column in seperate lists ( a list for time and another list for stress ) . and then use this lists to do some other mathematical operations and . . . my problem is how to create this lists ! my text file is as follows : (the first line of the text file and the four lines from the bottom of that is empty!)

              X               FORCE-1     

            0.                 0.         
           10.E-03            98.3479E+03 
           12.5E-03          122.947E+03  
           15.E-03           147.416E+03  
           18.75E-03         183.805E+03  
           22.5E-03          215.356E+03  
           26.25E-03         217.503E+03  
           30.E-03           218.764E+03  
           33.75E-03         219.724E+03  
           37.5E-03          220.503E+03  
           43.125E-03        221.938E+03  
           51.5625E-03       228.526E+03  
           61.5625E-03       233.812E+03  

Solution

  • You can read your file line by line

    time = []
    stress = []
    count =0
    with open("textfile.txt") as file:
        for line in file:
            line = line.strip() #removing extra spaces
            temp = line.split(" ")
            if count>=3 and temp[0].strip() : #checking empty string as well
               time.append(temp[0].strip())  #removing extra spaces and append
               stress.append(temp[len(temp)-1].strip()) #removing extra spaces and append
            count+=1
    
    print time
    

    Output running above script

    ['0.', '10.E-03', '12.5E-03', '15.E-03', '18.75E-03', '22.5E-03', '26.25E-03', '30.E-03', '33.75E-03', '37.5E-03', '43.125E-03', '51.5625E-03', '61.5625E-03']