python - 使用python处理和创建外部软件的输入文件

标签 python numpy io file-handling

当我编程时,我经常使用外部软件进行繁重的计算,然后用 Python 分析结果。这些外部软件通常是 Fortran、C 或 C++,它们通过为它们提供输入文件来工作。这可以是一个小文件,说明执行特定计算的模式,也可以是一个它必须处理的大数据文件。这些文件通常使用某种格式(数据列之间有很多空格)。例如下面给出了我目前使用的一个数据文件。

This is a header. The first line is always a header...
  7352.103      26.0      2.61    -8.397                         11.2
  7353.510      26.0      4.73    -1.570                          3.5
  7356.643      26.0      5.75    -2.964                          9.0
  7356.648      26.0      5.35    -3.187                          9.0
  7364.034      26.0      5.67    -5.508                          1.7
  7382.523      26.0      5.61    -3.935                          1.9

我的问题是是否存在一个 Python 库来创建此类输入文件,通过阅读模板(由同事提供或来自外部软件的文档)?

通常,我的所有列都采用 NumPy 格式,并希望将其提供给创建输入文件的函数,以模板为例。我不是在寻找一种蛮力方法,它会很快变得丑陋。

我不确定要在这里搜索什么,如有任何帮助,我们将不胜感激。

最佳答案

我基本上可以用 savetxt 复制你的样本。它的 fmt 变量为我提供了 FORTRAN 代码用于读取和写入文件的相同类型的格式控制。它以与 FORTRAN 和 C print 相同的方式保留空格。

import numpy as np

example = """
This is a header. The first line is always a header...
  7352.103      26.0      2.61    -8.397                         11.2
...
"""

lines = example.split('\n')[1:]
header = lines[0]
data = []
for line in lines[1:]:
  if len(line):
    data.append([float(x) for x in line.split()])
data = np.array(data)

fmt = '%10.3f %9.1f %9.2f %9.3f %20.1f'  # similar to a FORTRAN format statment
filename = 'stack21865757.txt'

with open(filename,'w') as f:
  np.savetxt(f, data, fmt, header=header)

with open(filename) as f:
  print f.read()

制作:

# This is a header. The first line is always a header...
  7352.103      26.0      2.61    -8.397                 11.2
  7353.510      26.0      4.73    -1.570                  3.5
...

编辑

这是一个将示例行转换为格式的粗略脚本:

import re
tmplt = '  7352.103      26.0      2.61    -8.397                         11.2'
def fmt_from_template(tmplt):
    pat = r'( *-?\d+\.(\d+))' # one number with its decimal
    fmt = []
    while tmplt:
        match = re.search(pat,tmplt)
        if match:
            x = len(match.group(1)) # length of the whole number
            d = len(match.group(2)) # length of decimals
            fmt += ['%%%d.%df'%(x,d)]
            tmplt = tmplt[x:]
    fmt = ''.join(fmt)
    return fmt
print fmt_from_template(tmplt)
# %10.3f%10.1f%10.2f%10.3f%29.1f

关于python - 使用python处理和创建外部软件的输入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21865757/

相关文章:

numpy - 为 Matplotlib 的 LineCollection 构建段列表

python - sklearn标签编码器: TypeError : '<' not supported between instances of 'int' and 'str'

python - 无效的实例 ID : An error occurred (InvalidInstanceId) when calling the SendCommand operation

python - 在单元格中写入带有分隔符的 CSV 文件(两点)

python - 如何使用 Sympy 分离方程的实部和虚部?

java - 抽象类 InputStream 的实例

java - 始终重新初始化 PrintWriter 而不关闭是个好主意吗?

python - 在不加载到内存的情况下查找保存的 numpy 数组(.npy 或 .npz)的形状

python - 错误 : 'int' object is not subscriptable - Python

python - 如何从字典中删除比 python 中的特定长度短的键?