如何将输入文本文件中的各个列保存到 python 中的各个输出文本文件

how to save individual columns from an input text file to individual output text files in python

我刚开始使用 python (anaconda3),但我无法弄清楚 应该 下面的问题真的很简单...我已经搜索过了在互联网上到处寻找解决方案,但我找不到。

目标: 我希望我的脚本将输入文本文件中的各个列(通过 --column 索引)写入相应的输出文本文件。用户可以 select 任意数量的列(具有匹配数量的输出文件)。

示例:python septc.py --infile infile.txt --column 0 2 3 --outfile out1.txt out2.txt out3.txt

我的问题:

  1. 如何在各自的输出文件中保存由 --column 向量定义的输入文件的单个列?
  2. 用户给出的 col 索引号可能会减去 1,因为用户从 1 开始计算 col,而 python 从 0 开始,所以选择最后一个 col 会越界...虽然我可以在脚本的帮助文件中说计数从 0 开始。

下面的脚本应该打印 infile 的第 1、第 3 和第 4t col,它确实这样做了,但是它将所有三个 col 写入每个输出文件而不是第 1 col 写入 out1.txt,第 3列为 out2.txt,第 4 列为 out3.txt。这是 bc 对外部循环的每个实例执行内部循环。同样,更改循环顺序会在每个输出文件中写入第 4 列,这不是我想要的。我尝试了其他方法(例如,for c in np.nditer(col))但无济于事。

我怀疑这种 for 循环方法在这里不合适。它应该类似于 for c in col write c into associated text file...但是如何 link a col 及其输出文件?!

非常感谢您的帮助!

提前致谢,

尼克

cols = [0,2,3]
data = np.arange(20).reshape(5,4)
np.savetxt('infile.txt', data, delimiter='  ', fmt='%1.0f')
f = np.loadtxt('infile.txt')
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.],
       [ 16.,  17.,  18.,  19.]])

######### Script (shorter version) #########
#!/usr/bin/env python
import numpy as np
import sys
import argparse
# Parse cmd line arguments
p = argparse.ArgumentParser()
p.add_argument('--infile', nargs='?', action="store", default=sys.stdin)
p.add_argument('--column', nargs='+', action="store", type=int)
p.add_argument('--outfile', nargs='+', action="store", default=sys.stdout)
nargs = p.parse_args()
# Assign cmd line arguments to variables
col = nargs.column
outfile = nargs.outfile
infile = nargs.infile
with open(infile) as infile:
    data = np.loadtxt(infile)
# This is supposed to save each col into its respective output file ... supposed to ...
for out in outfile:
    with open(out, 'wb') as f:
        for c in col:
            y = data[:,c]
            np.savetxt(f, y, fmt='%1.0f')

您正在遍历每个输出文件的所有列。尝试使用 zip 在列和输出文件之间建立关系。然后将各个列的文本保存到各个文件中。

查看有关内置函数的更多信息 zip here

for out, c in zip(outfile,col):
    with open(out, 'wb') as f:
        y = data[:,c]            
        np.savetxt(f, y, fmt='%1.0f')

希望这对您有所帮助。

结果:

$ python col2files.py  --infile infile.txt --column 0 2 3 --outfile out1.txt out2.txt out3.txt

$ cat out1.txt
0
4
8
12
16

$ cat out2.txt
2
6
10
14
18

$ cat out3.txt
3
7
11
15
19