【问题标题】:Read text file and write file from specific contents从特定内容读取文本文件和写入文件
【发布时间】:2014-01-29 20:14:36
【问题描述】:

我想从文本文件创建和写入新文件。 我面临的挑战是如何获取特定列的内容。

输入文件有问题。

例如,

input.txt(制表符分隔:行的总列数不同)

CATEGORY      NEIGHBOUR        NUMBER1   NUMBER2     TOTAL
city          Washington    30        50          80
county        mountain      in        seattle     10        4         30
community     church        men       15          5         4

output.txt(我想要创建的。每行 3 列)

CATEGORY                      NUMBER1      TOTAL    
city Washington               30           80
county mountain in seattle    10           30 
community church men          15           4

这样写该怎么办?

【问题讨论】:

  • 虽然定义明确,但到目前为止您还没有真正向我们展示过您尝试过的内容吗?可以吗?
  • Python Parse CSV Correctly 的可能重复项
  • 您真的关心列的左对齐,还是制表符分隔的输出就足够了?

标签: python parsing


【解决方案1】:

你可以试试这个python脚本:

file_in  = open('input.txt', 'r')
file_out = open('output.txt', 'w')

for line in file_in:
    line = line.rstrip()
    line = line.split('\t')

    CATEGORY = ' '.join(line[:-3]) ##set variable as beginning of line 
                                   ##to before 3rd last column
    NUMBER_1 = line[-3] ##set variable as 3rd last column
    TOTAL = line[-1]    ##set variable as last column

    file_out.write('%s\t%s\t%s\n' % (CATEGORY, NUMBER_1, TOTAL))

file_in.close()
file_out.close()
  • 运行脚本:python <ABOVE_SCRIPT>.py(假设 input.txt 与脚本在同一目录中)
  • 输出将在 output.txt 的标题行中返回“NEIGHBOUR”...您可以随时删除它

【讨论】:

    【解决方案2】:

    试试这样的:

    lines = open('in_file', 'r').readlines()
    for line in lines:
        fields = line.split('\t')
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多