How to validate csv file?

后端 未结 4 781
感情败类
感情败类 2020-12-05 11:29

How can we validate a CSV file ?

I have an CSV file of structure:

Date;Id;Shown
15-Mar-10;231;345
15-Mar-10;232;346
and so on and on !!! approx arou         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 12:22

    I wrote an open source Python tool to simplify validation of such files available from http://pypi.python.org/pypi/cutplace/.

    The basic idea is that you describe the data format in a structured interface specification using OpenOffice.org, Excel or plain CSV. This is done in a few minutes and legible enough to serve as documentation too. We use it to validate files with about 200.000 rows on a daily base.

    You can validate a CSV file using the command line:

    cutplace specification.csv data.csv
    

    In case invalid data rows are found, the exit code is 1. If you need more control, you can write a little Python script that imports the cutplace module and adds a listener for validation events.

    As example, here's a specification that would validate the sample data you provided, filling the gaps of your short description by making a few assumptions. (I'm writing the specification in CSV to inline it in this post. In practice I prefer OpenOffice.org's Calc and ODS because I can use more formating and make it easier to read and maintain.)

    ,"Interface: Show statistics"
    ,
    ,"Data format"
    "D","Format","CSV"
    "D","Item delimiter",";"
    "D","Header","1"
    "D","Encoding","ASCII"
    ,
    ,"Fields"
    ,"Name","Example","Empty","Length","Type","Rule"
    "F","date","15-Mar-10",,,"RegEx","\d\d-[A-Z][a-z][a-z]-\d\d"
    "F","id","231",,,"Integer","0:"
    "F","shown","345",,,"Integer","0:"
    ,
    ,"Checks"
    ,"Description","Type","Rule"
    "C","id per date must be unique","IsUnique","date, id"
    

    Lines starting with "D" describe the basic data format. In this case it is a CSV file using ";" as delimiter with 1 header line in ASCII encoding.

    Lines starting with "F" describe the various fields. For example,

    ,"Name","Example","Empty","Length","Type","Rule"
    "F","id","231",,,"Integer","0:"
    

    defines a mandatory field "id" of type Integer with a value of 0 or greater. To allow the field to be empty, specify an "X" in the "Empty" column:

    ,"Name","Example","Empty","Length","Type","Rule"
    "F","id","231","X",,"Integer","0:"
    

    Finally there is an optional section to contain more advances checks spawning the whole file, not only single rows. For example, if each date in your file must provide date for an id only once, you can state this using:

    ,"Description","Type","Rule"
    "C","id per date must be unique","IsUnique","date, id"
    

    Any row that starts with an empty column can contain any text you like and will not be processed during validation. This is useful for headings, comments and so on.

提交回复
热议问题