How To ...‎ > ‎

CSV Files

Working with CSV Files 
CSV files are files with each item separated with commas 
    e.g. first, last, addr, phone
           Mike, Smith, 19 Main Street, 301-111-2222
           Sally, Jones, 10 South St, 222-333-4444

If there is a comma in the field, then quotes are put around the entire field.
     e.g. full name, addr, phone
            "Smith, Mike",   19 Main Street, 301-111-2222
            " Jones, Sally", 10 South St, 222-333-4444

LiveCode identifies each field as an item
    e.g.  item 1 = full name
            item 2 = addr
            item 3 = phone

1. Reading In Files

    Reading a CSV File - Knowing the filename:
        put URL ("File:/Users/example/scores.csv") into field "FileIn"    - puts it into a field called "FileIn"
            or
        put URL ("File:/Users/example/scores.csv") into x     - puts it into a variable called x


    Reading a CSV File - Selecting the file
        
    Only CSV file:
    local tFile
    answer file "Select the File to load:"  with type "Comma Separated Values|CSV"
    put it into tFile
    if tFile is empty then 
        exit mouseUp
    else
        put URL ("file:" & tFile) into field "fileIn"
    end if


    see the Dictionary for other more information

2. Writing Out Files

    Writing a CSV File - Knowing the filename:
        put x into URL ("File:/Users/example/scores.csv")    
            or
        put field "FileIn" into URL ("File:/Users/example/scores.csv")    
 

    Writing a CSV File - Selecting the file name    
         ask file "Save to?"  with type "Comma Separated Values|CSV"
    put it into tFile
    if tFile is empty then 
        exit mouseUp
    else
        put field "fileIn" into URL ("file:" & tFile)
    end if


    see the Dictionary for other more information
 

3. Converting to different types

    Changing to Tab Delimited (to work with, or to put into a table field)
        replace comma with tab in xData       (the file is in a variable called xData)
                 or
        replace comma with tab in field "fileIn"        (the file is in a field called "fileIn")
 

     Changing to Data Grid (to work with, or to put into a Data Grid field)
       where x is the variable we put our file into,  

        put line 1 of field "x" into tColumnTitles
        replace comma with return in  tColumnTitles
            set the dgProp["columns"] of group "text" to tColumnTitles
            replace comma with tab in x
            set the dgText[true] of group "text" to tFileContents 

3. Working With CSV Text

    Sorting a CSV File - by the first item:
        set the itemDelimiter to comma
        sort lines of field "fileIn" by item 1    

    Looping through each line of a CSV File:
        repeat for each line L in field "fileIn"
            if item 1 of L = ... then
                ....
            end if
        end repeat

  
Comments