使用python合并csv文件出错了

时间:2014-06-20 21:30:17

标签: python csv

所以我使用以下代码:

def printname(x,m,y,n,z,R):
    name = x + str(m) + y + str(n) +  z + str(R)  + ".csv"
    return name

fout=open("out.csv","a")

for k in [0.9, 0.8, 0.75, 0.6, 0.5, 0.4, 0.2, 0.1]:# n
    for j in [0.,5.,10.,30.,70.,80.,100.]: # R  
        f = open(printname("minTm",0.0,"n",k,"R",j))
        f.next() # skip the header
        for line in f:
            fout.write(line)
        f.close() # not really needed
fout.close()

我正在使用printname函数创建文件名,其格式为minTm0.0nkRj 其中k和j迭代,如上面的for循环所示。

一切都适用于合并文件,只是我丢失了我的csv文件的第一行。 csv文件的示例如下:

m=,0.0,R=,0.0

Tmin,Tmax,s,a,tmp
5000,10000.0,[ -4.06784730e-10],[ 1.5],0.0060940149762198454
7500,10000.0,[ 0.],[ 1.5],0.0058371331958134804
8750,10000.0,[ -2.00167591e-06],[ 1.5],0.0057109512367820173
9375,10000.0,[ -5.81705152e-06],[ 1.5],0.0056484231992318433
9687,10000.0,[ 0.],[ 1.5],0.0056173494163291524
9843,10000.0,[ -9.33496371e-16],[ 1.5],0.0056018475131042059
9921,10000.0,[ -8.29812062e-15],[ 1.5],0.0055941053050743194
9960,10000.0,[ -3.01889438e-06],[ 1.5],0.0055902363865212969
9980,10000.0,[ -5.86201413e-06],[ 1.5],0.0055882528908336284
9990,10000.0,[ -2.57259293e-18],[ 1.5],0.0055872612866520906
9995,10000.0,[ -8.29261958e-08],[ 1.5],0.0055867655204772633
9997,10000.0,[ -4.17256457e-06],[ 1.5],0.0055865672207120942
9998,10000.0,[ -6.70360888e-06],[ 1.5],0.0055864680722669735
9999,10000.0,[ -1.02650006e-11],[ 1.5],0.0055863689247764216
,
Tmin= ,9999,s=,[ -1.02650006e-11],a=,[ 1.5],tmp=,0.0055863689247764216

第一行显示m的值,R对最终文件至关重要。我似乎无法想到算法遗漏它的任何原因。有任何想法吗?没有行f.next()运行代码并得到相同的结果。

2 个答案:

答案 0 :(得分:0)

在输出文件中,您是否丢失了所有输入文件的第一行?因为看起来如果你在代码中取出f.next()行,输出的第一行应该输出,但它可能会附加到前一个输入条目的最后一行。如果是这种情况,您可以尝试在读入每个输入文件后添加额外的换行符:

for k in [0.9, 0.8, 0.75, 0.6, 0.5, 0.4, 0.2, 0.1]:# n
for j in [0.,5.,10.,30.,70.,80.,100.]: # R  
    f = open(printname("minTm",0.0,"n",k,"R",j))
    for line in f:
        fout.write(line)
    fout.write('\n')
    f.close() # not really needed
fout.close()

答案 1 :(得分:0)

好的,我明白了:

fout=open("out.csv","a")
for k in [0.9, 0.8, 0.75, 0.6, 0.5, 0.4, 0.2, 0.1]:# n
    for j in [0.,5.,10.,30.,70.,80.,100.]: # R  
        f = open(printname("minTm",0.0,"n",k,"R",j), 'r+')
        lines = f.readlines()
        for i in range(0, len(lines)):
            line = lines[i]
            fout.write(line)
fout.close()

感谢您的建议。