我想从文本文件创建和编写新文件。 我遇到的挑战是如何获取特定列的内容。
输入文件搞砸了。
例如,
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
我该怎么做才能这样写?
答案 0 :(得分: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 与脚本位于同一目录中)答案 1 :(得分:0)
尝试这样的事情:
lines = open('in_file', 'r').readlines()
for line in lines:
fields = line.split('\t')
...