How adjust width of cell of csv file in python? -
i using code write csv file
import csv data = [[1,'more width cell',3],[4,5,6],[7,8,9]] item_length = len(data[0]) open('test.csv', 'wb') test_file: file_writer = csv.writer(test_file) in range(item_length): file_writer.writerow([x[i] 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 cell have same width. how can increase width of more width cell cell?
rows written sequentially need know ahead of time column width each column be. might require iterating on data before output determine width of each column.
once you've determined column width, can format output column according required width. use of python string.format() function gives lot of flexibility.
something might work:
def expanded_row_data(row_data, col_widths): """return list of strings, modified column widths `col_width` list of integer column widths. """ return [ '{0:<{width}}'.format(d, width=width) (d, width) in zip(row_data, col_widths) ] col_widths = calc_col_width(data) # <--- write function determine column widths. open('test.csv', 'wb') test_file: file_writer = csv.writer(test_file) in range(item_length): file_writer.writerow(expanded_row_data([x[i] x in data], col_widths))
Comments
Post a Comment