简体   繁体   中英

How to write .csv file in Python?

I am running the following: output.to_csv("hi.csv") where output is a pandas dataframe.

My variables all have values but when I run this in iPython, no file is created. What should I do?

Better give the complete path for your output csv file. May be that you are checking in a wrong folder.

I'm not sure if this will be useful to you, but I write to CSV files frequenly in python. Here is an example generating random vectors (X, V, Z) values and writing them to a CSV, using the CSV module. (The paths are os paths are for OSX but you should get the idea even on a different os.

Working Writing Python to CSV example

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()

Hopefully there is something useful in here for you!

You have to make sure that your 'to_csv' method of 'output' object has a write-file function implemented.

And there is a lib for csv manipulation in python, so you dont need to handle all the work:

https://docs.python.org/2/library/csv.html

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