如何在python中将输入文本文件中的各个列保存到各个输出文本文件中
我刚刚开始使用python(anaconda3),但我不知道下面的问题应该很简单。。。我在互联网上到处寻找解决方案,但找不到 目标:我希望脚本将输入文本文件中的各个列(通过--column索引)写入相应的输出文本文件中。用户可以选择任意数量的列(具有匹配数量的输出文件) 示例:python septc.py--infle infle.txt--column 0 2 3--outfile out1.txt out2.txt out3.txt 我的问题:如何在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
您正在迭代每个输出文件的所有列。尝试使用
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