gpt4 book ai didi

python - 如何在Python中的前两个打印行之间添加一行破折号?

转载 作者:行者123 更新时间:2023-11-30 22:03:34 25 4
gpt4 key购买 nike

我正在尝试从 csv 文件在控制台中创建一个表。为了使输出看起来更像表格,我想在第二行添加一行破折号来分割标题和主表格内容。

这是我到目前为止的代码:

import csv

with open('filename.csv', mode='r') as csv_file:
csv_reader = csv.reader(csv_file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print("|",row[0]," "*(20-len(row[0])), "|",
row[1], " " * (15 - len(row[1])), "|",
row[2], " " * (20 - len(row[2])), "|",
row[3], " " * (5 - len(row[3])), "|")

这是输出:

| Track           | Artist           | Album                 | Time   |
| Songname 1 | Artist 1 | Album 1 | 7:15 |
| Songname 1 | Artist 2 | Album 2 | 6:27 |
| Songname 1 | Artist 3 | Album 3 | 5:24 |
| Songname 1 | Artist 4 | Album 4 | 2:50 |
| Songname 1 | Artist 5 | Album 5 | 4:39 |
| Songname 1 | Artist 6 | Album 6 | 5:11 |
| Songname 1 | Artist 7 | Album 7 | 2:56 |
| Songname 1 | Artist 8 | Album 8 | 4:29 |
| Songname 1 | Artist 9 | Album 9 | 3:17 |
| Songname 1 | Artist 10 | Album 10 | 3:04 |

Process finished with exit code 0

这是我想要实现的输出:

-----------------------------------------------------------------------
| Track | Artist | Album | Time |
-----------------------------------------------------------------------
| Songname 1 | Artist 1 | Album 1 | 7:15 |
| Songname 1 | Artist 2 | Album 2 | 6:27 |
| Songname 1 | Artist 3 | Album 3 | 5:24 |
| Songname 1 | Artist 4 | Album 4 | 2:50 |
| Songname 1 | Artist 5 | Album 5 | 4:39 |
| Songname 1 | Artist 6 | Album 6 | 5:11 |
| Songname 1 | Artist 7 | Album 7 | 2:56 |
| Songname 1 | Artist 8 | Album 8 | 4:29 |
| Songname 1 | Artist 9 | Album 9 | 3:17 |
| Songname 1 | Artist 10 | Album 10 | 3:04 |
-----------------------------------------------------------------------

最佳答案

您可以使用 string format mini language 让您的代码变得更加简单:

t = """Track,Artist,Album,Time
Songname 1,Artist 1,Album 1,7:15
Songname 1,Artist 2,Album 2,6:27
"""
with open("t.txt","w") as w:
w.write(t)


import csv

with open('t.txt', mode='r') as csv_file:
csv_reader = csv.reader(csv_file)
for idx, row in enumerate(csv_reader):
if idx == 0:
print("-"*65)

# string format mini language:
# {:<20} means take the n-th provided value and right align in 20 spaces
print("|{:<20}|{:<15}|{:<20}|{:<5}|".format(*row)) # *row == row element wise
if idx == 0:
print("-"*65)
print("-"*65)

输出:

-----------------------------------------------------------------
|Track |Artist |Album |Time |
-----------------------------------------------------------------
|Songname 1 |Artist 1 |Album 1 |7:15 |
|Songname 1 |Artist 2 |Album 2 |6:27 |
-----------------------------------------------------------------
<小时/>

如果您想省略行时间并使用自适应宽度而无需硬编码长度,则标题提取的替代解决方案:

演示文件:

t = """Track,Artist,Album,Time
Very Long Songname 1,Artist 1,Album 1,7:15
Songname 1,Artist 2,Album 2 title with epic proportions,6:27
"""
with open("t.txt","w") as w:
w.write(t)

代码:

import csv

def get_format_string(w):
s = '|'+'|'.join(" {{:<{}}} ".format(l) for _,l in sorted(w.items()))+'|'
return s.format

def get_widths(reader,filehandle):
"""Calculate maximum widths of columns. Rewinds filehandle to seek(0)."""
widths = {}
for row in reader:
for i,c in enumerate(row):
widths[i] = max(widths.get(i,0), len(c))
# rewind
filehandle.seek(0)
return widths

with open('t.txt', mode='r') as csv_file:
csv_reader = csv.reader(csv_file)
fmt = get_format_string(get_widths(csv_reader,csv_file))

header = fmt(*(next(csv_reader)))
w = len(header)
print("-"*w)
print(header)
print("-"*w)

# deal with the rest of the data
for row in csv_reader:
print(fmt(*row))

# and the last line
print("-"*w)

输出:

--------------------------------------------------------------------------------
| Track | Artist | Album | Time |
--------------------------------------------------------------------------------
| Very Long Songname 1 | Artist 1 | Album 1 | 7:15 |
| Songname 1 | Artist 2 | Album 2 title with epic proportions | 6:27 |
--------------------------------------------------------------------------------

关于python - 如何在Python中的前两个打印行之间添加一行破折号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com