How to write .csv file in Python?
我运行的是:
我的变量都有值,但是当我在IPython中运行它时,不会创建任何文件。我该怎么办?
最好给出输出csv文件的完整路径。可能是您签入了错误的文件夹。
我不确定这是否对您有用,但我经常用python编写csv文件。下面是一个生成随机向量(x,v,z)值并使用csv模块将其写入csv的示例。(路径是OS路径,用于OSX,但即使在不同的OS上,您也应该了解这个想法。
编写python到csv示例1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import os, csv, random # Generates random vectors and writes them to a CSV file WriteFile = True # Write CSV file if true - useful for testing CSVFileName ="DataOutput.csv" CSVfile = open(os.path.join('/Users/Si/Desktop/', CSVFileName), 'w') def genlist(): # Generates a list of random vectors global v, ListLength ListLength = 25 #Amount of vectors to be produced Max = 100 #Maximum range value x = [] #Empty x vector list y = [] #Empty y vector list z = [] #Empty x vector list v = [] #Empty xyz vector list for i in xrange (ListLength): rnd = random.randrange(0,(Max)) #Generate random number x.append(rnd) #Add it to x list for i in xrange (ListLength): rnd = random.randrange(0,(Max)) y.append(rnd) #Add it to y list for i in xrange (ListLength): rnd = random.randrange(0,(Max)) #Generate random number z.append(rnd) #Add it to z list for i in xrange (ListLength): merge = x[i], y[i],z[i] # Merge x[i], y[i], x[i] v.append(merge) #Add merged list into v list def writeCSV(): # Write Vectors to CSV file wr = csv.writer(CSVfile, quoting = csv.QUOTE_MINIMAL, dialect='excel') wr.writerow(('Point Number', 'X Vector', 'Y Vector', 'Z Vector')) for i in xrange (ListLength): wr.writerow((i+1, v[i][0], v[i][1], v[i][2])) print"Data written to", CSVfile genlist() if WriteFile is True: writeCSV() |
希望这里有一些对你有用的东西!
必须确保"output"对象的"to-csv"方法实现了一个写文件函数。
在python中有一个用于csv操作的lib,因此您不需要处理所有的工作:
https://docs.python.org/2/library/csv.html网站