【问题标题】:Python column manipulation in a text file.文本文件中的 Python 列操作。
【发布时间】:2016-04-02 04:21:37
【问题描述】:

我有一个输入文件:

A03 58  0   0   0   -9
A03 59  0   0   0   -9
A03 60  0   0   0   -9
A03 61  0   0   0   -9
A03 62  0   0   0   -9
A03 63  0   0   0   -9
A03 64  0   0   0   -9
A03 65  0   0   0   -9
A03 66  0   0   0   -9
A03 67  0   0   0   -9
A03 68  0   0   0   -9
A03 69  0   0   0   -9
A03 70  0   0   0   -9
A03 71  0   0   0   -9
A03 72  0   0   0   -9
A03 73  0   0   0   -9
A03 74  0   0   0   -9

我想要的输出:

A03_58 A03_58 0 0 0 -9
A03_59 A03_59 0 0 0 -9
A03_60 A03_60 0 0 0 -9 

输出将考虑 inputfile 中的第二列,在第一列和该字母添加下划线。然后把它复制到第二列。 我确实知道如何复制这样的列:

# with open('inputfile.txt') as inputs:
#     for line in inputs:
#         parts = line.strip().split()
#         print("{0} {1}".format(parts[0], " ".join(parts)))

但是,在使用上述脚本之前,我需要先更改列并删除第二列。

在读入大型输入文件后,我不确定如何处理这个问题。浏览了一些索引问题,但找不到答案。

【问题讨论】:

    标签: python if-statement for-loop indexing


    【解决方案1】:
    import csv
    
    with open('in.txt') as in_, open('out.csv', 'wb') as out:
        writer = csv.writer(out, delimiter=' ')
    
        for line in in_:
            row = line.split()
            first_col = '{}_{}'.format(row[0], row[1])
            writer.writerow([first_col, first_col] + row[2:])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      相关资源
      最近更新 更多