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

如何在python中将输入文本文件中的各个列保存到各个输出文本文件中,python,arrays,for-loop,text-files,nested-loops,Python,Arrays,For Loop,Text Files,Nested Loops,我刚刚开始使用python(anaconda3),但我不知道下面的问题应该很简单。。。我在互联网上到处寻找解决方案,但找不到 目标:我希望脚本将输入文本文件中的各个列(通过--column索引)写入相应的输出文本文件中。用户可以选择任意数量的列(具有匹配数量的输出文件) 示例:python septc.py--infle infle.txt--column 0 2 3--outfile out1.txt out2.txt out3.txt 我的问题: 如何在相应的输出文件中保存由--column

我刚刚开始使用python(anaconda3),但我不知道下面的问题应该很简单。。。我在互联网上到处寻找解决方案,但找不到

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

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

我的问题:

  • 如何在相应的输出文件中保存由--column向量定义的输入文件的各个col
  • 用户给出的col的索引数可能会减少1,因为用户从1开始计算col,而python从0开始计算col,所以选择最后一个col是不允许的……尽管我可以在脚本的帮助文件中说,计算从0开始
  • 下面的脚本应该打印infle的第1列、第3列和第4t列,但它会将所有三列写入每个输出文件,而不是将第1列写入out1.txt,将第3列写入out2.txt,将第4列写入out3.txt。这是bc,内部循环对外部循环的每个实例执行。类似地,更改循环顺序会在每个输出文件中写入第4列,这不是我想要的。我尝试过其他方法(例如,对于np.nditer(col)中的c),但没有效果

    我怀疑这种for-loop方法在这里不合适。它应该类似于将c写入关联的文本文件中的c…但如何将一个列与其输出文件链接

    我真的很感激你的帮助

    提前多谢各位

    Nic


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

    有关内置函数的详细信息,请参见
    zip

    希望这有帮助

    结果:

    $ 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
    

    哎呀,非常感谢你。。。我确实试过zip(),但一定是用错了。再次感谢你!
    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