【问题标题】:how to save individual columns from an input text file to individual output text files in python如何将输入文本文件中的单个列保存到python中的单个输出文本文件
【发布时间】:2018-03-29 01:48:34
【问题描述】:

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

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

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

我的问题:

  1. 如何在各个输出文件中保存由 --column 向量定义的输入文件的各个列?
  2. 当用户从 1 开始计数 col 而 python 从 0 开始计数时,用户给出的 col 的索引号可能会减少 1,因此选择最后一个 col 将超出范围...尽管我可以在帮助中说以 0 开头的脚本文件。

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

我怀疑这种 for 循环方法在这里不合适。它应该类似于 for c in col 将 c 写入关联的文本文件...但是如何将 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')

【问题讨论】:

    标签: python arrays for-loop text-files nested-loops


    【解决方案1】:

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

    查看更多关于内置函数ziphere

    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
    

    【讨论】:

    • Yippieh,非常感谢! ...我确实在某个时候尝试过 zip() ,但一定是用错了。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2013-07-05
    • 2019-05-04
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多