简体   繁体   中英

Python 2.7 Export csv file with data

I am trying to export my data into a csv file

My code is as follows

x1=1
x2=2
y1=1
y2=4
z1=1
z2=2 

a = (x1,y1,z1)
b = (x2,y2,z2)
def distance(x1,y1,z1,x2,y2,z2):
 return (((x2-x1)**2)+((y2-y1)**2)+((z2-z1)**2))**0.5
w=distance(x1,y1,z1,x2,y2,z2)
print w
if w>1 and w<2:
    time = 1
if w>2 and w<3:
    time = 2
if w>3 and w<4:
    time = 3

import csv

with open('concert_time.csv', 'w') as output:

I am stuck at this last line. I would like a file with two columns for 'Letter Combinations' and 'Time', and the output to look like:

Letters         Time
a and b           3

I know there is a way to get this output by explicitly labeling a row as '3' for the appropriate time, but I would like a csv file that will change if I change the values of a or b, and thus the value of 'time' would change. I have tried

writer.writerows(enumerate(range(time), 1))

but this does not get me the desired output (in fact it is probably very far off, but I am new to Python so my methods have been guess and check)

Any help is greatly appreciated!

completing your code for csv writer. Also make sure to open file as wb on windows so that carriage return (newline) is added automatically.

with open('concert_time.csv', 'wb') as output:
    writer = csv.writer(output)
    writer.writerow(["Letter Combinations", "Time"]) #header
    writer.writerow(["a and b", time]) #data

Content of concert_time.csv :

Letter Combinations,Time
a and b,3

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