[英]How adjust width of cell of csv file in python?
我正在使用此代码编写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])
现在输出是
1 ,4,7
more,5,8
3 ,6,9
我想要
1, ,4,7
more width cell ,5,8
3 ,6,9
现在所有单元格都具有相同的宽度。 如何增加宽度更大的单元格的宽度 ?
现在输出是
1,more,7 2,5,8 3,6,9
不,这不对。 当我运行您的代码时,我得到
1,4,7
more width cell,5,8
3,6,9
...这是应该的。 适当的CSV文件就是-用逗号分隔的值,没有填充。 它没有“长度”的概念,只是每个值都有一个特定的长度,该长度只是该特定值的长度。 如果您想将第一列填充到特定长度,则将值更改为填充(即,将"1"
类的值替换为"1 "
-为消除歧义添加引号)。
行是按顺序写入的,因此您需要提前知道每列的列宽。 这可能需要对数据进行遍历,然后再进行输出以确定每列的宽度。
一旦确定了列宽,就可以根据所需的宽度来格式化该列的输出。 Python string.format()函数的使用为您提供了很大的灵活性。
这样的事情可能会起作用:
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.