作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试从 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/
我是一名优秀的程序员,十分优秀!