简体   繁体   English

如何在python中调整csv文件的单元格宽度?

[英]How adjust width of cell of csv file in python?

I am using this code to write csv file 我正在使用此代码编写csv文件

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. 适当的CSV文件就是-用逗号分隔的值,没有填充。 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). 如果您想将第一列填充到特定长度,则将值更改为填充(即,将"1"类的值替换为"1 " -为消除歧义添加引号)。

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. Python string.format()函数的使用为您提供了很大的灵活性。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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