使用csv.writer()创建具有两列的文件(csv)

时间:2014-04-01 19:08:04

标签: python csv

我是一个完全的初学者并尝试使用两列(yPlus和uPlus的值)创建文件erg.csv:

yPlus  uPlus
separated by a \t.



result:
0 " new line
"
0 " new line
"
2 . 4 6 0 7 3 " 
"
2 . 4 6 0 7 3 " 
"
4 . 9 2 1 4 6 " 
"
4 . 9 2 1 4 6 " 
"

...

而不是:

0 \t 0
2.46073 \t 2.4607
4.92146 \t 4.92146
...



def create_file():

    f_in = open("folder/experiment.xy","r")
    f_out = open("erg.csv","w",encoding="utf8")
    writer = csv.writer(f_out,delimiter=" ")


    while 1:
        zeile = f_in.readline()

        if len(zeile) == 0:break

        expr = r"\s(?P<yPlus>[0-9.]*\n)"
        erg = re.search(expr,zeile)
        yPlus = erg.group('yPlus')
        yPlus = str(yPlus)

        if type(erg.group('yPlus')) == str:

            if float(yPlus) <= 12:
                writer.writerows([yPlus] + [yPlus])
                #rowstr = "{0:s}\t{1:s}".format(yPlus,yPlus)
                #writer.writerows([yPlus,yPlus])

            else:
                uPlus = calc_uPlus(float(yPlus))
                #uPlus = str(uPlus)
                rowstr = "{0:s}\t{1:6.2f}".format(yPlus,uPlus)
                writer.writerows(rowstr)

        else:
            print("Stop! type(erg.group('yPlus') no string.")


    f_in.close()
    f_out.close()


def calc_uPlus(yP):
    uP = ( 2.439 * math.log(yP) + 5.2 )
    return(uP)

我尝试使用两个版本未能成功获得所需的结果:

writer.writerows([yPlus] + [yPlus])

rowstr = "{0:s}\t{1:6.2f}".format(yPlus,uPlus)
writer.writerows(rowstr)

有人可以帮忙吗? 非常感谢!

1 个答案:

答案 0 :(得分:3)

如果yplusuplus分别是左右列,则需要事先将它们合并使用writerows

import csv
c = csv.writer(open("file.csv", "wb"), delimiter="\t")
yplus = [1, 2]
uplus = [3, 4]
c.writerows(zip(yplus, uplus))

或者,如果您更愿意使用writerow而不是writerows

for l, r in zip(yplus, uplus):
    c.writerow([l,r])

以上都会输出:

1\t2
3\t4