我正在尝试从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 |
-----------------------------------------------------------------------
答案 0 :(得分:2)
您可以使用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 |
--------------------------------------------------------------------------------
答案 1 :(得分:1)
我相信您要实现的目标是表的标题(即列名)应分开显示。如果我理解正确,那么我建议为什么不使用pandas.read_csv导入您的csv文件。它会自己识别标题,如果没有,它将作为参数选择如何选择行作为标题。
查看文档: Pandas- read_csv
此外,如果万一您只想用破折号或您所说的方式,那么我相信您将必须在打印具有列名的第一行后添加打印语句,然后再对破折号添加另一个打印语句,然后循环以获得其他信息,然后再打印最终破折号。是的,这是一种手动方式。
编辑: 由于您要求手动执行此操作,因此代码如下:
import csv
with open('stacko.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter='|')
line_count = 0
print("-----------------------------------------------------------------------------------")
for row in csv_reader:
if line_count == 0:
print("|",row[1], " " * (5 - len(row[1])), "|",
row[2], " " * (10 - len(row[2])), "|",
row[3], " " * (5 - len(row[3])), "|",
row[4], " " * (5 - len(row[4])), "|")
print("-----------------------------------------------------------------------------------")
line_count=1
else:
print("|",row[1], " " * (5 - len(row[1])), "|",
row[2], " " * (10 - len(row[2])), "|",
row[3], " " * (5 - len(row[3])), "|",
row[4], " " * (5 - len(row[4])), "|")
print("-----------------------------------------------------------------------------------")
输出:
-----------------------------------------------------------------------------------
| 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 |
-----------------------------------------------------------------------------------