简体   繁体   English

Python 2.7导出包含数据的CSV文件

[英]Python 2.7 Export csv file with data

I am trying to export my data into a csv file 我正在尝试将数据导出到csv文件中

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: 我想要一个包含“ Letter Combinations”和“ Time”两列的文件,其输出应类似于:

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. 我知道有一种方法可以通过在适当的时间将行显式标记为'3'来获得此输出,但是我想要一个csv文件,如果我更改a或b的值(因此更改'的值)时间会改变。 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) 但这并不能为我提供所需的输出(实际上可能相距很远,但是我是Python的新手,所以我的方法已经过猜测和检查)

Any help is greatly appreciated! 任何帮助是极大的赞赏!

completing your code for csv writer. csv writer完成代码。 Also make sure to open file as wb on windows so that carriage return (newline) is added automatically. 还要确保在Windows上以wb格式打开文件,以便自动添加回车符(换行符)。

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 : concert_time.csv内容:

Letter Combinations,Time
a and b,3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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