0

I am trying to convert a .csv file in Python/ArcPy to dBase format.

I am using this code:

import arcpy
inputcsv = "D:/2016_08_21.csv"
outputfolder = "D:/"
arcpy.TableToDBASE_conversion(inputcsv, outputfolder)

That works but the problem is that the first field in the CSV ("DWD_ID") does not always contain integers. At first the IDs start like 10321 and so on but eventually there are letters too. However the Conversion tool recognizes the first value in the field as an integer and sets the field as integer type and later on the other values are kicked out and never appear in the .DBF.

Is there a better way to convert a .csv to .dbf or can I explicitly define the field "DWD_ID" as Text?

I have tried the DBF module of python but I have not been able to successfully convert a csv file to dBase. My output file was always empty. I am only seeking programmatic solutions in Python; I do not want to use any other software.

  • You have to cheat, by making 1 st dummy line in your csv with obvious types, e.g. first value in DWD_ID column should contain letters. "AAA" will do. This Q was asked multiple times – FelixIP Sep 6 '16 at 20:03
  • 1
    You may want do some research using schema .ini file to pre-define the field types. – artwork21 Sep 6 '16 at 23:37
  • Silly ESRI. You'd think they'd build their tools to address this sort of thing, instead of making thousands of people stumble upon the same error (and probably thousands more that never notice it) and then each develop some convoluted work-around. – Tom Sep 7 '16 at 15:19
2

So I have solved the problem like this then:

from shutil import copyfile
filename = "2016_08_21.csv"
inputcsv = r"D:/" + filename

# Create a dummy CSV file in a temp folder
tempfolder = r"d:/Temp"
dummycsv = tempfolder + "/" + filename
copyfile(inputcsv, dummycsv)

# Open and read the original input-csv file
tempf1 = open(dummycsv, "r")
tempf1contents = tempf1.readlines()
tempf1.close()

dummyline = "AAAAA;27.07.1984;100;100;100;100;100;100;100;100;100;100\n"

# Create a dummy-line in the dummy-csv file in the first line
tempf1contents.insert(1, dummyline) 

# Write and save the new file
tempf1 = open(dummycsv, "w")
tempf1contents = "".join(tempf1contents)
tempf1.write(tempf1contents)
tempf1.close()

Worked perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.