Exporting list of values into csv or txt file using ArcPy?

You mention that you computed a list of values in a Python script, so the easiest way to dump that to a csv would be to use the csv module!

import csv

res = [x, y, z, ....]
csvfile = "<path to output csv or txt>"

#Assuming res is a flat list
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    for val in res:
        writer.writerow([val])    

#Assuming res is a list of lists
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(res)

QGIS 1.8 can't edit a CSV file. The workaround is to import the csv file into a db.sqlite table using QGIS's Qspatialite or Spatialite_GUI etc., and then edit the table and export that data back into a table.csv file, if necessary. In QGIS 1.8, DONT export or import into sqlite or spatialite directly from under LAYERS, via right-clicking. It is very slow and may crash. Use the Qspatialite plugin instead to load sqlite databases, and right click from Qspatialite to load into LAYERS for QGIS editing.

Alternately, you can right click on the table.csv file under your QGIS 1.8 LAYERS, export to shapefile, then load "vector" file, changing the file extension to ".*" to see ALL files available, including dbf without associated shapes. It loads the dbf table which can be edited, but if your column name or data widths exceed the shapefile/dbf limit then the data will be truncated. After importing back into a csv file, the table names can easily be restored with a text or spreadsheet editor, for instance Notepad, Gedit or Excel. That additional information is for the posterity of future folks looking over this question for an answer that suits their needs.


You could use pandas:

In [1]: import pandas as pd
        res = [[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd', 'e']]
        my_df = pd.DataFrame(res)
        my_df.to_csv('out.csv', index=False, header=False)
        print my_df

           0  1  2  3  4
        0  1  2  3  4  5
        1  a  b  c  d  e

pandas is a great module for easy data handling and analysis.

Tags:

Csv

Export

Arcpy