Python - 在对齐的列中打印 CSV 字符串列表
问题描述
我编写了一个完全兼容 Python 2
和 Python 3
的代码片段.我编写的片段解析数据并将输出构建为 CSV 字符串列表.
I have written a fragment of code that is fully compatible with both Python 2
and Python 3
. The fragment that I wrote parses data and it builds the output as a list of CSV strings.
脚本提供了一个选项来:
- 将数据写入
CSV 文件
,或 - 将其显示到
stdout
.
虽然在显示到 stdout
(第二个项目符号选项)时,我可以轻松地遍历列表并将 ,
替换为
,但这些项目长度是任意的,因此由于制表符的差异,请不要以很好的格式排列.
While I could easily iterate through the list and replace ,
with
when displaying to stdout
(second bullet option), the items are of arbitrary length, so don't line up in a nice format due to variances in tabs.
我做了很多研究,我相信字符串格式选项可以完成我所追求的.也就是说,我似乎找不到可以帮助我正确使用语法的示例.
I have done quite a bit of research, and I believe that string format options could accomplish what I'm after. That said, I can't seem to find an example that helps me get the syntax correct.
我宁愿不使用外部库.我知道如果我走这条路有很多可用的选项,但我希望脚本尽可能兼容和简单.
I would prefer to not use an external library. I am aware that there are many options available if I went that route, but I want the script to be as compatible and simple as possible.
这是一个例子:
value1,somevalue2,value3,reallylongvalue4,value5,superlongvalue6
value1,value2,reallylongvalue3,value4,value5,somevalue6
你能帮帮我吗?任何建议将不胜感激.
Can you help me please? Any suggestion will be much appreciated.
解决方案
import csv
from StringIO import StringIO
rows = list(csv.reader(StringIO(
'''value1,somevalue2,value3,reallylongvalue4,value5,superlongvalue6
value1,value2,reallylongvalue3,value4,value5,somevalue6''')))
widths = [max(len(row[i]) for row in rows) for i in range(len(rows[0]))]
for row in rows:
print(' | '.join(cell.ljust(width) for cell, width in zip(row, widths)))
输出:
value1 | somevalue2 | value3 | reallylongvalue4 | value5 | superlongvalue6
value1 | value2 | reallylongvalue3 | value4 | value5 | somevalue6
相关文章