从文本文件中提取数据(python)

时间:2017-03-26 09:53:52

标签: python split strip

我在文本文件中有两列数字,分别是时间和压力的列,我从abaqus有限元包中的分析得到它!我想在单独的列表中提取时间列和压力列(时间列表和另一个压力列表)。然后使用此列表进行其他一些数学运算。 。 。 我的问题是如何创建这个列表!我的文本文件如下:(文本文件的第一行和底部的四行是空的!)

              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  

1 个答案:

答案 0 :(得分:2)

您可以逐行阅读文件

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

输出在脚本上方运行

['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']