You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python读取CSV文件首行作为tabulate表格表头?

Python读取CSV并使用tabulate输出的表头问题解决

我尝试用Python编写代码读取CSV文件,并用tabulate模块在终端输出格式规整的表格。最初写的代码如下:

table = []
try:
    with open(filename) as csvfile:
        reader = csv.DictReader(csvfile)
        i = 0
        for row in reader:
            if (i == 0):
                headers = row
                i = 1
            table.append(row)
except FileNotFoundError:
    print("File not found.")
    sys.exit()
#output
print(tabulate(table, headers, tablefmt='grid'))

运行这段代码后发现,表格的表头用的是CSV文件的第二行而非第一行,导致输出的前两行内容重复。想知道怎么把CSV的第一行设为表格表头?


修正后的代码:

在得到帮助后,我把代码改成了下面的版本,现在可以正常运行了,感谢帮助。

table = []
try:
    with open(filename, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        headers = reader.fieldnames
        for row in reader:
            table.append(list(row.values()))
except FileNotFoundError:
    print("File not found.")
    sys.exit()

#output
print(tabulate(table, headers, tablefmt='grid'))

内容的提问来源于stack exchange,提问作者Doug

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:12:36