Python - Print list of CSV strings in aligned columns(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
这篇关于Python - 在对齐的列中打印 CSV 字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python - 在对齐的列中打印 CSV 字符串列表
基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01