如何从文本文件在python中创建表

时间:2017-07-09 16:09:31

标签: python

我一直在尝试从这样的文本文件中创建一个表:

MemberID  Surname  Year joined  Membership status  Nights booked  Pointsbalance
Jim123    jimmy     2017        gold               10              15000

,文本文件如下:

jim123,jimmy,2017,gold,10,15000

我该怎么做? 请尽可能简单

2 个答案:

答案 0 :(得分:0)

您可以读入数据并将其放入字典中:

f = open('filename.txt').readlines()

f = [i.strip('\n').split(',') for i in f]

final_data = {i[0]:i[1:] for i in f}

答案 1 :(得分:0)

如果您要将数据用于任何类型的分析,请尝试查看 Pandas 。看看这篇关于如何实现你想要做的伟大(和详细)的帖子:

https://chrisalbon.com/python/pandas_dataframe_importing_csv.html

这是您想要的代码(但请查看该URL以获取解释):

df = pd.read_csv('../data/jimmy.csv', names=['MemberID', 'Surname', 'Membership status', 'Nights booked', 'Pointsbalance'])

df

raw_data = {'MemberID': ['Jim123', 'Calamari123'],
        'Surname': ['jimmy', 'calamari'],
        'Membership status': ['gold', 'platinum'],
        'Nights booked': [10, 24],
        'Pointsbalance': ["15000", "94,000"]}
    df = pd.DataFrame(raw_data, columns = ['MemberID', 'Surname', 'Membership status', 'Nights booked', 'Pointsbalance'])