简体   繁体   English

格式化CSV数据输出?

[英]Formatting output of CSV data?

I'm fairly new to python and made something that had this output: (The text is in a csv file so so: 1,A 2,B 3,C etc) 我是python的新手,做了一些具有以下输出的内容:(文本位于csv文件中,因此:1,A 2,B 3,C等)

Number        Letter

1             A
2             B
3             C
26            Z

Unfortunately, I spent a good amount of time making it using a complicated method in which I manually made spaces like this: Updated Code rn 不幸的是,我花了很多时间使用一种复杂的方法来制作它,在这种方法中,我手动制作了这样的空格: 更新代码rn

fx = int(input('Number?\n'))
f=open('nums.txt','r')
lines=f.readlines()
line = lines[fx - 1]
with open('nums.txt','r') as f:
    for i, line in enumerate(f):
        if i >= 5: 
            break
        NUM, LTR, SMB = line.rsplit(',', 1)
        print(NUM.ljust(13) + LTR.ljust(13) + SMB)

How do I get it to make 3 columns? 如何获得3列? Right now it comes up with a 现在,它提出了一个

ValueError: not enough values to unpack (expected 3, got 2) 

So is there a simpler method of achieving this that doesn't move the strings around like this: 因此,有没有一种更简单的方法来实现此目的,而不会像这样移动字符串:

Number        Letter

1             A
2             B
3             C
26             Z #< string moves with spaces.

For simple alignment, you can use ljust or rjust . 为了简单对齐,可以使用ljustrjust There is also no need to read the entire file for each line you want to process: 您也无需为要处理的每一行读取整个文件:

with open('numberletter','r') as f:
    for i, line in enumerate(f):
        if i >= 5: 
            break
        number, letter = line.rsplit(',', 1)
        print(number.ljust(13) + letter)

For more complex output formatting, look at str.format() and the formatting syntax 有关更复杂的输出格式,请查看str.format()格式语法

You can use sys module for that. 您可以为此使用sys模块。

import sys
a=[1,"A"]
sys.stdout.write("%-6s %-50s " % (a[0],a[1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM