如何顺序读取和处理一组文本文件中的数据?

2024-05-18 06:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有50个文本文件(即Force1.txtForce2.txtForce50.txt)。文件如下所示:

0.0000000e+000 -1.4275799e-003  
2.0000000e-002 -1.1012760e-002  
4.0000000e-002 -1.0298970e-002  
6.0000000e-002 -8.9733599e-003  
8.0000000e-002 -9.6871497e-003  
1.0000000e-001 -1.2236400e-002  
1.2000000e-001 -1.4479739e-002  
1.4000000e-001 -1.3052160e-002  
1.6000000e-001 -1.1216700e-002  
1.8000000e-001 -8.6674497e-003  
2.0000000e-001 -8.6674497e-003  
2.2000000e-001 -1.3358070e-002  
2.4000000e-001 -1.7946720e-002  
2.6000000e-001 -1.9782179e-002

我希望从Force1.txt读取数据,将数据存储在元组列表中,并分析这些数据(这种分析的细节与问题无关)。然后我必须对Force2.txtForce3.txt等执行相同的操作。在

以下是我的尝试:

^{pr2}$

我得到了这个错误:

'Table', smooth=SOLVER_DEFAULT, timeSpan=STEP):
Invalid time values, expected monotonically increasing numbers

我如何解决这个问题?在


Tags: 文件数据txt列表错误table读取数据细节
1条回答
网友
1楼 · 发布于 2024-05-18 06:34:07

该代码应:

import os

def load_data(fn):
    with open(fn) as f:     
        lines = f.readlines() 
    return [tuple(map(float, x)) for x in [row.split() for row in lines]]

def display_data(lst):
    return lst.__repr__().replace('[', '').replace(']', '')

dirname = r"Your dir name goes here"

for filename in os.listdir(dirname):
    if filename.endswith('.txt'):
        if filename.startswith('Force'):     
            pathfile = os.path.join(dirname, filename)
            print pathfile
            pp = load_data(pathfile)
            print display_data(pp)    
            mdb.models['Model-1'].TabularAmplitude(data=pp, 
                                                   name='Table', 
                                                   smooth=SOLVER_DEFAULT, 
                                                   timeSpan=STEP)

您只需要用包含文本文件的目录名更新dirname。我建议您不要使用file作为变量标识符,因为file是Python中的保留字。我用了filename。在

相关问题 更多 >