list=("Member ID, Surname, Year joined, Nights booked, Membership status, Points balance")
f = open("SampleData2017.txt")
print(list)
for surname in f.readlines():
print(surname)
然而,当我运行它时,项目只用逗号分隔,而不是在每个副标题下
我希望它看起来像:
MemberID Surname Year joined Membershipstatus Nightsbooked Points balance
Gri33415 Griffiths 2015 Gold 35 40000
Smi22316 Smith 2016 Silver 3 7500
我该如何解决这个问题?请尽可能简单
答案 0 :(得分:0)
听起来你有一个标题列表,还有一个表格,其中包含你从SampleData2017.txt
提取的数据。我使用了一个名为tabulate
的第三方模块,因为它让我不必为简单的任务编写一堆代码。
在命令行上使用pip从pypi安装它。
$ pip install tabulate
或在Python3上
$ pip3 install tabulate
然后编写代码:
import tabulate
headers = map(str.strip, "Member ID, Surname, Year joined, Nights booked, Membership status, Points balance".split(","))
# or just format it yourself:
headers = ("Member ID", "Surname", "Year joined", "Nights booked",
"Membership status", "Points balance")
with open("SampleData2017.txt") as f:
# you never say how each row is split into fields, so I'm assuming here
# that it's comma-separated and calling str.split(",") on each
table = tabulate.tabulate((line.split(",") for line in f), headers=headers)
在此处使用我的示例数据,输出为:
>>> headers = ("one", "two", "three")
>>> data = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
>>> print(tabulate.tabulate(data, headers=headers))
one two three
----- ----- -------
1 2 3
4 5 6
7 8 9
答案 1 :(得分:0)
我猜你可以使用csv模块内置的python来实现你想要的东西
编辑1:
Observe标头最初分配为字符串,然后转换为列表
添加了对每个项目的信息,以便了解如何实现这一目标,但绝对不是您想要的精确对齐方式。
import csv
headers="Member ID, Surname, Year joined, Nights booked, Membership status, Points balance"
headers = headers.split(',')
print ('\t'.join(x.ljust(5) for x in headers))
with open('WorkingDirectory\stars.csv', 'r') as mycsv:
rows = csv.reader(mycsv)
for row in rows:
print ('\t'.join(x.ljust(15) for x in row))
原始答案:
import csv
headers=["Member ID, Surname, Year joined, Nights booked, Membership status, Points balance"]
print ('\t'.join(headers))
with open('SampleData2017.txt', 'r') as mycsv:
rows = csv.reader(mycsv)
for row in rows:
print ('\t'.join(row))
输出:
Member ID, Surname, Year joined, Nights booked, Membership status, Points balance
Gri33415 Griffiths 2015 Gold 35 40000
Smi22316 Smith 2016 Silver 3 7500