# Exporting mesh as CSV file

I have been using this script to export my mesh to a CSV file. The problem is that every time I select a new object, the file is overwritten, so ideally when selecting a new object I need it to write a new CSV file, perhaps like this. "mesh_001.csv", "mesh_002.csv" etc. Please could someone assist.

import bpy

outputFile = 'C:/My_Objects/mesh.csv'

verts = [ bpy.context.object.matrix_world @ v.co for v in bpy.context.object.data.vertices ]

csvLines = [ ";".join([ str(v) for v in co ]) + "\n" for co in verts ]

f = open( outputFile, 'w' )
f.writelines( csvLines )
f.close()


# Use the name of the object as the file name

import bpy
import os

name = bpy.context.object.name
outputFile  = bpy.path.abspath("//csv_export\\" + name + ".csv")

print(outputFile)


If I save my file in D:\ and my object is named Cube, the outputFile will be D:\csv_export\Cube.csv.

# Increase a suffix number for each export

import bpy
import os

index = 0
while True:
path = "//csv_export\\mesh" + str(index).zfill(4) + ".csv"
outputFile = bpy.path.abspath(path)
if not os.path.exists(outputFile):
break
index += 1

print(outputFile)


In this script, we initially construct a path to a file with the suffix 0 => mesh0000.csv. While a file already exists at that location, we increase the counter.

• It doesn't seem to create the new directory D:/csv_export and if I create it myself nothing is written into it when I run the script. My .blend file is saved in the same D:/ directory. Maybe I'm doing something wrong? Mar 12 '20 at 10:02
• What code did you run? Was is this? Mar 12 '20 at 10:08
• Using the name of the object as file name. Mar 12 '20 at 11:15
• Do you comprehend the script you posted? Mar 12 '20 at 11:21
• I am not an expert at python, sorry. I sort of understand a few things. I am learning as I go. Mar 12 '20 at 11:33