简体   繁体   中英

using csv.writer() to create file (csv) with two columns

I am a complete beginner and try to create the file erg.csv with two columns (values of yPlus and uPlus):

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 " 
"

...

instead of:

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)

I've unsuccessfully tried, with two versions, to get the required result:

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

and

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

Could anybody help? Thank's a lot!

If yplus and uplus are the left and right column, respectively, you'll need to combine them beforehand to use writerows :

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

Or, if you'd rather use writerow instead of writerows :

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

The above will both output:

1\t2
3\t4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM