Python - 通过读取文件格式化输出的更有效方法

时间:2017-02-18 01:52:42

标签: python

我有一个包含以下内容的文本文件: (标题为:学生证,姓名,年龄,最喜欢的科目)

1234,Luke,15,History,
1256,Hannah,17,Maths,
1278,Katherine,14,Geography,
1290,Rachael,12,French,
3412,James,16,Computer Science,

我想要做的是将此文件的内容输出给用户,如下所示:

Student ID    Name          Age    Favourite Subject
1234          Luke          15     History
1256          Hannah        17     Maths
1278          Katherine     14     Geography
1290          Rachael       12     French
3412          James         16     Computer Science       

我现在的代码,如下所示,工作得很好(至少在我看来),但我猜这是一个更好的方法来做得更有效率?感觉我可能比必要时更加尴尬,附加到列表等。

def formatOutput():
    headings = ["Student ID", "Name", "Age", "Favourite Subject"]
    formatID = []
    formatName = []
    formatAge = []
    formatFavSub = []


    with open("Students.txt","r") as file:
        for line in file:
            info = line.split(",")
            formatID.append(info[0])
            formatName.append(info[1])
            formatAge.append(info[2])
            formatFavSub.append(info[3])

            formatOutput = [headings] + list(zip(formatID, formatName, formatAge, formatFavSub))


for i in formatOutput:
    print("{:<10}\t{:<9}\t{:<3}\t{:<17}".format(*i)) 

formatOutput()

帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:2)

保持简单:

template = "{:<10}\t{:<9}\t{:<3}\t{:<17}"
print(template.format("Student ID", "Name", "Age", "Favourite Subject"))
with open('Students.txt') as studentsfile:
    for line in studentsfile:
        print(template.format(*line.split(',')))

答案 1 :(得分:1)

我会使用Python csv模块读取器/写入器,或者DictReader / DictWriter。

来自Python csv document

>>> import csv
>>> with open('eggs.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

由于我现在有时间,我已经为我个人使用此代码添加了一个完整的解决方案:

import csv

def format_row(data=None, widths=None):
    return '\t'.join([column.ljust(width, ' ')
                    for column, width in zip(data, widths)])

heading = ("Student Id", "Name", "Age", "Favorite Subject")
widths = (10, 9, 3, 17)
output = []

output.append(format_row(heading, widths))

with open('Students.txt', 'r') as f:
    csv = csv.reader(f)
    for row in csv:
        output.append(format_row(row, widths))

for line in output:
    print(line)

format_row()方法使用列表推导来使用正确的间距格式化列。拉链将柱子与宽度相结合。这允许您相应地格式化每列。另请注意,在大多数情况下,您不希望空格分隔文件并添加制表符分隔符。但是,我添加了它们,因为这是您最初提出问题的方式。最后,您要添加一个检查以确保您有足够的行和宽度。如果没有,你最终会出错。