0

I'm writing a dictionary into a csv file using Python's csv library and a DictWriter object like so:

with open('test.csv', 'w', newline='') as fp:
    fieldnames = [<fieldnames for csv DictWriter>]

    dict_writer = csv.DictWriter(fp, fieldnames=fieldnames)
    dict_writer.writeheader()
    dict_writer.writerow(<some dictionary here>)

The result is that if i have a long name as one of the dictionary's values the cells look like this:

enter image description here

But i want it to look like this:

enter image description here

Is there a way to fit the cells' size to the string lengths ? I imagine this is a relatively common issue since you don't want to manually do it each time you open a csv file.

How can i fit it beforehand ?

Caffeine
  • 445
  • 1
  • 4
  • 16
  • 1
    The problem is related with the CSV reader that in your case seems to be Microsoft Excel. What about using another format which would allow you to do that, like XLS ( https://stackoverflow.com/questions/17326973/is-there-a-way-to-auto-adjust-excel-column-widths-with-pandas-excelwriter) – Ivan De Paz Centeno Jul 25 '18 at 06:58
  • 1
    CSV is a simple text format (open it in a text editor and you'll see), it contains no information on how a speadsheet program should display it. There are a several ways to make Excel auto-fit the column widths, check [this answer on Superuser](https://superuser.com/questions/1005062/automatic-column-width-in-excel). – zwer Jul 25 '18 at 06:59
  • Thank you ! :) the solution in the link (which works) is to use `StyleFrame` library which works wtih xlsx files and actually lets you modify the width of cells. Thanks – Caffeine Jul 25 '18 at 07:34

1 Answers1

4

A CSV does not have formatting information. It only have data. It is up to the viewer configuration how to resize the cells.

If you really need formatting, you should write in the file format of the receiving application (.ods, .xls, .xlsx...).

Poshi
  • 5,332
  • 3
  • 15
  • 32