Welcome, guest | Sign In | My Account | Store | Cart

uses a python csv package, but adds configuration file, so that the document, row and field tags can be specified. usage: python csv2xml.py -p propertyFile -i inputFile -o outputFile"

Python, 316 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import string,sys,os
import csv   #http://www.object-craft.com.au/projects/csv/
import getopt

# file props.py
from props import *

#rem download from http://object-craft.com.au/projects/csv

class csv2xml:
    """Given
    an input parameter of a property file and a CSV file,
    an output file name, 
    convert the CSV file to the output file
    according to the property definitions"""

    propsFile="" #properties file name
    
    inputFile="" #input file name
    infile =0 # handle

    outputFile="" # output file name
    outfile = 0  #output file handle
    
    
    # Standard XML declaration
    PROLOG = "<?xml version=\"1.0\"?>"
    # Start tag 
    OPEN_START = "<"
    # end tag 
    OPEN_END = "</"
    # Close  
    CLOSE = ">"
    # newline 
    NEWLINE = "\n"
    #indentation  
    INDENT = "  "
    #Field Delimiter property; from property Fielddelimiter 
    fldDelimiter=""
    # Row delimiter property : from property Rowdelimiter 
    rowDelimiter=""
    #Number of fields per row
    nfields=0
    #Number of rows (by calculation)
    nrows = 0
    #Header, the xml decl, doctype etc.
    header1,header2,header3= "","",""
    #tag to use for each row.
    rowname=""
    #tag to use for root of output document
    rootname=""
    #tags to use for successive fields
    fieldnames={}


    #debug
    debug=0;
    debug2=0;
    def __init__ (self):
         version="0.3";
         print "csv2xml, version ",version
         self.propsFile=""
         self.inputFile=""
         self.outputFile=""
         self.fieldnames.clear()


    def usage(self):
        print self.__doc__
        print "Usage: csv2xml -p propertyFile -i inputFile -o outputFile"
        


    def checkFiles(self, inFile,outFile,pFile):
        #print "Outfile is: ", outFile
        if not(os.access(inFile, os.R_OK | os.F_OK)):
            print "\tNo read access to Input File ",inFile, "Quitting"
            sys.exit(2)
        if not(os.access(outFile,  os.F_OK)):
            print "output file does not exist, creating it"
            self.outfile=open(outFile, 'w')
            self.outfile.close();
        if not(os.access(pFile, os.R_OK|os.F_OK)):
               print "\tNo read access to Properties File ",pFile, "Quitting"
               sys.exit(2)
        return 1

            
    def setParameters(self, props):
        """ Load up the global parameter attributes.

        Loads the global properties from the props class.

        params: props - An instance of class props.



        """

        
        self.fldDelimiter = props.getProperty("head","fielddelimiter","X")
        self.rowDelimiter = props.getProperty("head","rowdelimiter","X")
        self.rootname = props.getProperty("head","rootname")
        self.rowname = props.getProperty("head","recordname")
        if self.debug:
            print "RowDelim[" , self.rowDelimiter , "]"
        self.dtd = props.getProperty("head","dtd","null")
        self.comment = props.getProperty("head","comment")
        if (self.fldDelimiter == "X"):
	    print "Warning: Property file error: Fielddelimiter not set, using comma"
        self.fldDelimiter=","

        if (self.rowDelimiter[0] == 'X'):
            print "Warning: Property file error: Rowdelimiter not set, using NewLine"
        self.rowDelimiter="\n"
        
        self.header1 = self.PROLOG + self.NEWLINE
        if (self.dtd != ""):
            self.header2 ="<!DOCTYPE " + self.rootname + 
            " SYSTEM " +"\""+ self.dtd + "\""+ ">"+  self.NEWLINE + 
            self.NEWLINE
            self.header3 ="<!-- " + self.comment + " -->" + self.NEWLINE
        self.nfields = props.getProperty("head","fields")

        if self.debug2:
            print "setParameters: ",self.nfields
        for i in range(int(self.nfields)):
            fieldref = "field" + str(i)
            #self.addProp(fieldref, props.getProperty('fields',fieldref))
            self.fieldnames[fieldref]=props.getProperty('fields',fieldref)
            if self.debug2:
                print "setParameters: ",props.getProperty('fields',fieldref)
        if self.debug2:
            print self.fieldnames.keys()

    def convert(self):
    #
    # *Convert the input file rows into XML,
    # * and  outputting.
    # *
    # *
    # **
        output =open(self.outputFile, 'w')
        output.write(self.header1+self.header2+self.header3)
        if self.debug:
            print "convert: writing to ", self.outputFile
            print "convert: reading fm: ", self.inputFile
        output.write(self.OPEN_START+self.rootname+self.CLOSE)  #ROOT tag
    
    #
        p = csv.parser()
        f = open(self.inputFile,'r')
        nrows = int(self.nfields) # number of fields
        #Read and parse input file till full record in hand as list
        
        while 1:
            line = f.readline()
            if not line:
                break
            rec = p.parse(line)
            if rec is not None:
                output.write(self.OPEN_START+self.rowname+self.CLOSE+self.NEWLINE) #<entry>
                idx = 0
                for fld in rec:
                    #idx = rec.index(fld)  #index of this item
                    nfld1 = string.replace(fld,"&","&amp;") # subst for &
                    nfld  = string.replace(nfld1,"£","&#x00A3;") # subst for £
                    tag = self.fieldnames['field'+str(idx)]
                    output.write(self.INDENT+self.OPEN_START+tag+self.CLOSE)
                    output.write(nfld)
                    output.write(self.OPEN_END+tag+self.CLOSE+self.NEWLINE)
                    idx += 1
                output.write(self.OPEN_END+self.rowname+self.CLOSE+self.NEWLINE)# </entry>
                
        output.write(self.OPEN_END+self.rootname+self.CLOSE)  #ROOT tag
        output.close()
    #################### Main #############################

    def main(self):
        if len(sys.argv) < 3:
            self.usage()
            sys.exit(2)
        try:
            opts,args = getopt.getopt(sys.argv[1:],"i:o:p:h",["help","input=","output=","properties="])
        except getopt.GetoptError:
            self.usage()
            print "Option Exception"
            sys.exit(2)

        indexFile=""
        searchPattern=""
        for o, a in opts:
            if self.debug:
                print "main:",o,a
            if o in ("-h","--h","-help"):
                usage()
                sys.exit()
            if o in ("-p","--p","--properties"):
                self.propsFile= a # set properties file
            if o in ("-i","--i","--input"):
                self.inputFile = a
            if o in ("-o","--o","--output"):
                self.outputFile=a  # set output file
                
        if (self.debug):
            print "Input File      ",self.inputFile
            print "Properties File ",self.propsFile
            print "Output File     ",self.outputFile

        if self.checkFiles(self.inputFile,self.outputFile,self.propsFile):
            if (self.debug):
                print "Files All OK"
            #set  file handles for files
            self.outfile = file(self.outputFile, 'w')
            self.infile  = file(self.inputFile, 'r')
            print "\tConverting "+self.inputFile+" using "+self.propsFile
            if (self.debug):
                print "Files opened."
            #instantiate the properties.
                
            myprops= props(self.propsFile)
            self.setParameters(myprops)
            
            self.convert() # convert the file.
            if self.debug:
                print "Mycsv: Done"


            
if __name__ == "__main__":
    con=csv2xml()
    con.main()
   

#====================================================================

Seperate class, probably should be included in the main file.
This reads a configuration file of the form:

The header group adds a comment, specifies the field and
row delimiters to be expected (\n should not be changed)
the recordname is the row tag.
The number of fields specifies the number of fields to expect.
  This format is specified in one of the RFC's. 


[head]
comment=Generated using CSVToXML
fielddelimiter=,
rowdelimiter=\n
rootname=products
recordname=entry
fields=35

[fields]
field0 =ProdID
field1 =Prod_Code
field2 =Print_Name
field3 =Prod_Name
field4 =Add_Info
field5 =Desc_Info
field6 =Description
field7 =Audience_Other
field8 =Product_Type
field9 =SectionID
field10 =SectionID2
field11 =Related_Products
field12 =Related_Sections1
field13 =Related_Sections2
field14 =Related_Sections3
#====================================================================


import ConfigParser
import sys

#
# Properties file  props.py. Works in conjuction with
# pcatsCSV.py to extract properties from a properties file.
#
#Only method, retrieve a named property from the properties file
# format of props file as per java 
# addition, comment as per python

class props:
    """ Mimic the java getProperties """
    handle = ""  # file handle for property.
    debug = 0
    def __init__ (self,propsFileName):
        if self.debug:
            print "props: Init called on : ",propsFileName
       
        try:
            self.handle=ConfigParser.ConfigParser()
            self.handle.readfp(open (propsFileName))
        except:
            print "\tprops: Error reading properties file, quitting"
            sys.exit(2)
            
        if self.debug:
            print "props: Done reading"


            
    def getProperty (self,sect, proName, *defaultValue):
        val = ""
        try:
            val = self.handle.get(sect,proName)
        except (ConfigParser.NoOptionError):
            print "props.getProperty, Property \""+ proName+ "\" Not found"
        if self.debug:
            if val=="":
               print "props.getProperty[", proName, "]Not found" 
            else:
                print "props.getProperty, [", proName, "] Value ", val
        return val
        


   

3 comments

Dave Pawson (author) 19 years, 1 month ago  # | flag

Source Attribution. Sorry, I should have said: The idea of using an external properties file came from Danny Ayers, http://www.isacat.net/2001/code/CSVtoXML.htm and I used those ideas, until I found the ConfigParser python module, which makes use of the win32 ini file format.

dulipwithanage 10 years, 7 months ago  # | flag

i get an error

C:\data\programs\python-csv-2-xml>C:\Python26\python.exe recipe-159100-1.py -i i nputFile -p properties -o out csv2xml, version 0.3 Converting inputFile using properties props.getProperty, Property "dtd" Not found Traceback (most recent call last): File "recipe-159100-1.py", line 230, in <module> con.main() File "recipe-159100-1.py", line 222, in main self.convert() # convert the file. File "recipe-159100-1.py", line 149, in convert p = csv.parser() AttributeError: 'module' object has no attribute 'parser'

dulipwithanage 10 years, 7 months ago  # | flag

seems like , i have done something wrong there.

Created by Dave Pawson on Fri, 25 Oct 2002 (PSF)
Python recipes (4591)
Dave Pawson's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks