pythonstringarrayscsv

Python csv string to array


Any simple library or function to parse a csv encoded string and turn it into an array or dictionary?

All the built in csv module examples take filepaths, not strings.


Solution

  • You can convert a string to a file object using io.StringIO and then pass that to the csv module:

    from io import StringIO
    import csv
    
    scsv = """text,with,Polish,non-Latin,letters
    1,2,3,4,5,6
    a,b,c,d,e,f
    gęś,zółty,wąż,idzie,wąską,dróżką,
    """
    
    f = StringIO(scsv)
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print('\t'.join(row))
    

    simpler version with split() on newlines:

    reader = csv.reader(scsv.split('\n'), delimiter=',')
    for row in reader:
        print('\t'.join(row))
    

    Or you can simply split() this string into lines using \n as separator, and then split() each line into values, but this way you must be aware of quoting, so using csv module is preferred.

    On Python 2 you have to import StringIO as

    from StringIO import StringIO
    

    instead.