Writing a nice formatted csv file

Discussion in 'Python' started by redcic, May 2, 2007.

  1. redcic

    redcic Guest

    Hi all,

    I use the csv module of Python to write a file. My code is of the
    form :

    cw = csv.writer(open("out.txt", "wb"))
    cw.writerow([1,2,3])
    cw.writerow([10,20,30])

    And i get an out.txt file looking like:
    1,2,3
    10,20,30

    Whereas what I'd like to get is:
    1, 2, 3,
    10, 20, 30

    which is more readable.

    Can anybody help me to do so ?

    Thanks,

    Cédric
     
    redcic, May 2, 2007
    #1
    1. Advertisements

  2. redcic

    7stud Guest

    cvs files are constructed for efficient processing not formatting so
    that you can read them easier. If you want a formatted file, then
    construct one.
     
    7stud, May 2, 2007
    #2
    1. Advertisements

  3. The idea behind csv module is to produce and read csv files that are
    "machine readable" rather than "human readable", so I think you should
    write the file "by hand" to take into account those whitespace.
     
    Sebastian Bassi, May 2, 2007
    #3
  4. redcic

    redcic Guest

    Well then how can I format a file ?

    Thanks for your help,

    Cédric

     
    redcic, May 2, 2007
    #4
  5. redcic

    dustin Guest

    for row in rows:
    print "".join([ "%-6s" % ("%d," % cell) for cell in row ])

    The "%-6s" formats each column to be no less than six characters long;
    the "%d," formats the number with a comma after it.

    This won't be quite what you want, since you've comma-aligned all of the
    fields after the first, but it should be readable.
    <snip>
     
    dustin, May 2, 2007
    #5
  6. redcic

    Jon Clements Guest

    How about pre-formatting the columns before hand before using
    something like:

    # List of formatting to apply to each column (change this to suit)
    format = ['%03d', '%10s', '%10s']

    data = [1, 10, 100]
    print [fmt % d for fmt,d in zip(format,data)]

    Results in: ['001', ' 10', ' 100']

    Then write that using the CSV module.

    hth

    Jon.
     
    Jon Clements, May 2, 2007
    #6
  7. redcic

    Dave Borne Guest

    Whereas what I'd like to get is:
    (without trying this myself first...)
    You might try setting up a csv dialect with a delimiter of ',\t' then
    using a reader that can set tab stops for display.

    -Dave
     
    Dave Borne, May 2, 2007
    #7
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.