用python消除文本文件中的空行

时间:2017-03-26 11:34:15

标签: python lines

我在文本文件中有两列数字,分别是时间和压力的列,我从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  

用于提取时间和压力数据以及为每个数据创建单独列表的代码如下:

time = []
stress = []
count = 0
with open('txtFORCE-1.txt') as file:
    for line in file:
        line = line.strip() #removing extra spaces from right and left 
        temp = line.split(" ") # spliting the result of the last line
        if count>=3 :
           time.append(temp[0].strip())  #removing extra spaces and append
           stress.append(temp[0].strip()) #removing extra spaces and append
        count=count+1

print(time)
print(stress)

我没有使用此代码,我从我的朋友那里得到这个代码,而且我不确定它的准确性!

1 个答案:

答案 0 :(得分:1)

以下是修订后的代码,可以回答有关从最终列表中删除空项目的问题。

time = []
stress = []
with open('txtFORCE-1.txt') as file:
    for count, line in enumerate(file):
        temp = line.split()  # remove extra spaces and split
        if count >= 2 and len(temp) > 1:
           time.append(temp[0])
           stress.append(temp[1])

print(time)
print(stress)

删除空项目的更改是if count >= 2 and len(temp) > 1:,如果该行不包含至少两个项目,则不执行任何操作。我也跳过前两行(你的代码跳过三行),改进了行的分割,并使其他一些行更加pythonic。请注意,两个列表都包含字符串,而不是数字如果您改为使用time.append(float(temp[0]))等,则可以更改,但如果任何项目实际上不是正确格式的数字,则会失败。