2010-08-13 68 views
1

我有制表符分隔的数据,我将选定的几列导出到另一个文件中。我有:追加数据列

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) 

我在做什么错???它为什么重复?

PLease help

Thanks!

回答

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) 
+0

太谢谢你了!我知道它必须是一件非常简单的事情。 – 2010-08-13 11:06:23

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.