Hi Everyone, I am trying to convert dbf to csv using the following code:
import arcpy import os import csv def DBFtoCSV(path): '''Convert every DBF table into CSV table. ''' arcpy.env.workspace = path tablelist=arcpy.ListTables('*', 'dBASE') for table in tablelist: outputFile = '{}.csv'.format(table.split('.dbf')[0]) # Get the fields in the dbf to use for the cursor and csv header row. fields = [] for field in arcpy.ListFields(table): fields.append(str(field.name)) # Make the csv. with open((os.path.join(path,outputFile)),'wb') as output: dataWriter = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) # Write header row. dataWriter.writerow(fields) # Write each row of data to the csv. with arcpy.da.SearchCursor(table, fields) as cursor: for row in cursor: dataWriter.writerow(row) print('Finished creating {}'.format(outputFile)) if __name__ == '__main__': path=r'F:\DataLocation' DBFtoCSV(path)
I am getting an error at the SearchCursor because it says field names must be string or non empty. I added the print statement and it turns out my list of fields is empty. Can anyone tell me why this is?
ListFields—Help | ArcGIS for Desktop
Can you format your code to make it easier to read. Also what is the table name when it prints?
Thanks Dan,
I have formatted the code. When I print the table name it gives me "filename.dbf" The filename matches exactly with the name in the path directory.
I suspect it can't find a file, hence no fields, you will need a specific path
The path in the above code is just to protect the privacy of the directory and the data that I am working with. The actual path name leads to a folder with many files including dbf and non dbf. The print table then lists the file inside that directory. Does this help?
Ok... if the path is correct and the file is a dbase file, and its name prints out, you should be able to get a list of the fields using the syntax in the help... but you say it doesn't work (ps, the field.name, is a string already so no str is needed)
Correct. Removed the string. It seems to be grabbing the file, but does not list the fields.
Did you forget to include a real path?
path=r'path'
Darren,
Thanks for checking. The actual code has the full path name spelled out, just put that there for privacy.
Have you inspected the dBase files within ArcGIS? Possibly a problem in the files themselves?