我有一个包含以下内容的文本文件: (标题为:学号、姓名、年龄、最喜欢的科目)
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()
谢谢你的帮助。谢谢!你知道吗
保持简单:
我将使用Python csv模块reader/writer或DictReader/DictWriter。你知道吗
从Python csv document:
由于我现在有时间,我已经添加了一个完整的解决方案,说明我个人如何使用此代码:
format_row()方法使用列表理解来格式化具有正确间距的列。zip将列与其宽度相结合。这允许您相应地格式化每一列。另外请注意,在大多数情况下,您不希望对文件进行空格分隔,也不希望添加制表符分隔符。但是,我添加了它们,因为这是您最初提出问题的方式。最后,您需要添加一个检查,以确保您有足够的行和宽度。否则,你将以一个错误告终。你知道吗
相关问题 更多 >
编程相关推荐