排序并存储文本文件?

时间:2014-04-15 00:23:22

标签: python sorting

我正在尝试对以下信息进行排序和存储,这些信息将从txt文件中读取:

"Michael Jordan, 2/17/1963, basketball, Bulls
Alex Rodriguez, 7/27/1975, baseball, Yankees
Emmitt Smith, 3/15/1969, football, Cowboys"

这是我到目前为止的代码:

def main():
    athletes = []
    file = input("Please enter a file name: ")
    fn = open(file,mode='r')

我知道我需要填充数组,但是我如何分割txt文件,因为有空格和逗号?我希望数组保持[first name, last name, birthday, sport, team]

3 个答案:

答案 0 :(得分:1)

简单回答:

<强> string.split()

for line in fn:
    name, dob, sport, team = line.split(', ')

更复杂的答案:

使用csv模块。从一开始就有点复杂,但会让你更进一步。

答案 1 :(得分:1)

我会推荐numpy!

import numpy as np
my_array = np.genfromtxt('my_file.txt', dtype='str', delimiter=',')

答案 2 :(得分:0)

我明白了。我填写了清单,然后拆分名称。

for line in fn:
   x = line.split(', ')
   fullName = x[0]
   birthday = x[1]
   sport = x[2]
   team = x[3]

   fullNameSplit = fullName.split(" ")
   firstName = fullNameSplit[0]
   lastName = fullNameSplit[1]