writing fixed width, space delimited CSV output in Python

后端 未结 3 1586
栀梦
栀梦 2021-01-18 05:43

I would like to write a fixed width, space delimited and minimally quoted CSV file using Python\'s csv writer. An example of the output:

item1           item         


        
相关标签:
3条回答
  • 2021-01-18 06:08

    The basic problem you are running into is that csv and fixed-format are basically opposing views of data storage. Making them work together is not a common practice. Also, if you only have quotes on the items with spaces in them, it will throw off the alignment on those rows:

    testing     "rather hmm "
    strange     "ways to    "
    "store some " "csv data   "
    testing     testing    
    

    Reading that data back in results in wrong results as well:

    'testing' 'rather hmm '
    'strange' 'ways to    '
    'store some ' 'csv data   '
    'testing' 'testing' ''
    

    Notice the extra field at the end of the last row. Given these problems, I would go with your example of

    "item1          " "item2          "
    "next item1     " "next item2     "
    "anotheritem1   " "anotheritem2   "
    

    which I find very readable, is easy to generate with the existing csv library, and gets correctly parsed when read back in. Here's the code I used to generate it:

    import csv
    
    class SpaceCsv(csv.Dialect):
        "csv format for exporting tables"
        delimiter = None
        doublequote = True
        escapechar = None
        lineterminator = '\n'
        quotechar = '"'
        skipinitialspace = True
        quoting = csv.QUOTE_MINIMAL
    csv.register_dialect('space', SpaceCsv)
    
    data = (
            ('testing    ', 'rather hmm '),
            ('strange    ', 'ways to    '),
            ('store some ', 'csv data   '),
            ('testing    ', 'testing    '),
    
    temp = open(r'c:\tmp\fixed.csv', 'w')
    writer = csv.writer(temp, dialect='space')
    for row in data:
        writer.writerow(row)
    temp.close()
    

    You will, of course, need to have all your data padded to the same length, either before getting to the function that does all this, or in the function itself. Oh, and if you have numeric data you'll have to make padding allowances for that as well.

    0 讨论(0)
  • 2021-01-18 06:10

    What does this do for you? I think you really were only missing the csv.QUOTE_NONE constant.

    import csv
    csv.register_dialect('spacedelimitedfixedwidth', delimiter=' ', quoting=csv.QUOTE_NONE)
    with open('crappymainframe.out', 'rb') as f:
        reader = csv.reader(f, 'spacedelimitedfixedwidth')
    

    It's a modification on the unixpwd dialect example at the bottom of the csv module docs.

    0 讨论(0)
  • 2021-01-18 06:24

    This active state recipe shows how to output table-ized data in python: http://code.activestate.com/recipes/267662-table-indentation/

    You might be able to glean enough from that example to do what you want.

    0 讨论(0)
提交回复
热议问题