如何用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
相关产品推荐
相关产品推荐

