Python是一种更有效的格式化读取fi输出的方法

2024-09-27 20:17:34 发布

您现在位置: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()

谢谢你的帮助。谢谢!你知道吗


Tags: infohistorylukefrenchappendmathsgeographyhannah
5条回答

保持简单:

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(',')))

我将使用Python csv模块reader/writer或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()方法使用列表理解来格式化具有正确间距的列。zip将列与其宽度相结合。这允许您相应地格式化每一列。另外请注意,在大多数情况下,您不希望对文件进行空格分隔,也不希望添加制表符分隔符。但是,我添加了它们,因为这是您最初提出问题的方式。最后,您需要添加一个检查,以确保您有足够的行和宽度。否则,你将以一个错误告终。你知道吗

相关问题 更多 >

    热门问题