简体   繁体   中英

How adjust width of cell of csv file in python?

I am using this code to write csv file

import csv

data = [[1,'more width cell',3],[4,5,6],[7,8,9]]
item_length = len(data[0])

with open('test.csv', 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for i in range(item_length):
    file_writer.writerow([x[i] for x in data])

now output is

1   ,4,7
more,5,8
3   ,6,9

i want

 1,              ,4,7
 more width cell ,5,8
 3               ,6,9

Now all cell have same width. how can increase the width of more width cell cell?

now output is

 1,more,7 2,5,8 3,6,9 

No, it's not. When I run your code, I get

1,4,7
more width cell,5,8
3,6,9

... which is exactly as it should be. A proper CSV file is just that -- comma separated values, no padding. It does not have a concept of "length" except that each value has a particular length, which is simply the length of that particular value. If you want to pad the first column to a particular length then change the values to padded (ie replace a value like "1" with "1 " -- quotes added for disambiguation).

Rows are written sequentially so you need to know ahead of time what the column width for each column will be. This might require iterating over your data before output to determine the width of each column.

Once you've determined the column width, you can format the output for that column according to the required width. Use of the Python string.format() function gives you a lot of flexibility.

Something like this might work:

def expanded_row_data(row_data, col_widths):
    """Return list of strings, with modified column widths
    `col_width` is list of integer column widths.
    """
    return [ '{0:<{width}}'.format(d, width=width) for
      (d, width) in zip(row_data, col_widths) ]

col_widths = calc_col_width(data) # <--- Write this function to determine column widths.

with open('test.csv', 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for i in range(item_length):
    file_writer.writerow(expanded_row_data([x[i] for x in data], col_widths))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM