首页 > 解决方案 > 在 .dat 文件 python 中的特定列之间添加列

问题描述

我在目录中有大量具有不同行号和相同列号的文件。我想遍历所有文件并在特定列(4 和 5、12 和 13 之间)之间添加具有值(1.00)的新列。我想要编辑数据列并将其添加到相同的文件中。

我的数据看起来像

2.0 3.0 2.0 2.0 ...
1.0 0.0 2.0 1.0 ...
.
.
.

谢谢。

标签: pythonbashfile

解决方案


尝试这个:

import os

dir_path = './' # path to the required directory

def add_float(val, index, dat_file):
    lines = []
    with open(dat_file, 'r') as rd_file:
        for line in rd_file:
            line = line.strip().split()
            line.insert(index, str(val))
            lines.append(' '.join(line))

    with open(dat_file, 'w') as wrt_file:
        wrt_file.write('\n'.join(lines))

for file in filter(os.path.isfile, os.listdir(dir_path)):
    add_float(1.00, 3, file) # here, 1.00 is the value to be inserted after the 3rd column

推荐阅读