0

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!

1
  • you could first test your output by using print statements. try print '%s and %s,%s' % ( 'a','b',time) . When you have it ready, writing to a csv file is trivial. Commented Mar 29, 2017 at 2:21

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.