追加数据列
我有一些用制表符分隔的数据,我想把其中几个选定的列导出到另一个文件里。我的代码是:
a b c d
1 2 3 4
5 6 7 8
9 10 11 12
然后我得到的结果是:
b, d
b, d
2, 4
b, d
2, 4
6, 8
b, d
2, 4
6, 8
10, 12
......
我想要的结果是:
b, d
2, 4
6, 8
10, 12
我的代码是
f=open('data.txt', 'r')
f1=open('newdata.txt','w')
t=[]
for line in f.readlines():
line =line.split('\t')
t.append('%s,%s\n' %(line[0], line[3]))
f1.writelines(t)
我哪里出错了???为什么会重复?
请帮帮我
谢谢!!
2 个回答
1
正如之前提到的,最后一行的缩进不正确。此外,你的代码让事情变得复杂且容易出错。其实你不需要用到 t
这个列表,也不需要使用 f.readlines()
。
你的代码还有一个问题,就是 line[3]
这一部分会以换行符结尾(因为 readlines()
这类方法会在每行末尾保留换行符),而你在格式中又加了一个换行符 '%s,%s\n'
... 这样会导致你的输出文件出现双重换行,但你没有提到这一点。
另外,你说你想在第一行输出中得到 b, d
,并且你说你得到了 b, d
-- 可是你的代码显示的是 '%s,%s\n' %(line[0], line[3])
,这会输出 a,d
。注意两个不同之处:(1)缺少空格(2)输出的是 a
而不是 b
。
总的来说:你说你得到了 b, d\n
,但你展示的代码会输出 a,d\n\n
。下次请确保代码和输出是对应的。可以直接复制粘贴,不要凭记忆输入。
试试这个:
f = open('data.txt', 'r')
f1 = open('newdata.txt','w')
for line in f: # reading one line at a time
fields = line.rstrip('\n').split('\t')
# ... using rstrip to remove the newline.
# Re-using the name `line` as you did makes your script less clear.
f1.write('%s,%s\n' % (fields[0], fields[3]))
# Change the above line as needed to make it agree with your desired output.
f.close()
f1.close()
# Always close files when you have finished with them,
# especially files that you have written to.
4
你的缩进有问题,所以每次循环的时候都在写整个数组t,而不是等到最后再写。把它改成这样:
t=[]
for line in f.readlines():
line = line.split('\t')
t.append('%s,%s\n' % (line[0], line[3]))
f1.writelines(t)
另外,你也可以选择逐行写,而不是等到最后再写,这样就根本不需要数组 t
了。
for line in f.readlines():
line = line.split('\t')
s = '%s,%s\n' % (line[0], line[3])
f1.write(s)