Python:读取文件的各个元素

时间:2014-02-06 18:05:54

标签: python python-2.7 file-io

我试图读取文件的各个元素。在此示例中,每行的第一个元素是字典的键。接下来的五个元素将是列表形式中所述键的对应值。

max_points = [25, 25, 50, 25, 100]
assignments = ['hw ch 1', 'hw ch 2', 'quiz   ', 'hw ch 3', 'test']
students = {'#Max': max_points}

def load_records(students, filename):
    #loads student records from a file
    in_file = open(filename, "r")
    #run until break
    while True:
        #read line for each iteration
        in_line = in_file.readline()
        #ends while True
        if not in_line: break
        #deletes line read in
        in_line = in_line[:-1]
        #initialize grades list
        grades = [0]*len(students['#Max'])
        #set name and grades
        name, grades[0], grades[1], grades[2], grades[3], grades[4] = in_line.split()
        #add names and grades to dictionary
        students[name] = grades
        print name, students[name]


filename = 'C:\Python27\Python_prgms\Grades_list.txt'
print load_records(students, filename)

我现在拥有的方法非常洞穴,我想知道更优雅的循环方法是什么。我一直在寻找,但我似乎无法找到正确的迭代方法。帮助brotha。

2 个答案:

答案 0 :(得分:2)

另一种方法:

def load_records(students, filename):
    with open(filename) as f:
        for line in f:
            line = line.split()
            name = line[0]
            students[name] = map(int, line[1:])
            print name, students[name]

student字典虽然包含分数和参数#Max,但有一点似乎有点奇怪 - 一个关键字有两个含义,它是学生的名字还是参数的名字?可能更好地将它们分开。

答案 1 :(得分:0)

我的作业与去年类似。

def load_records(students, filename):
    file = open(filename, 'r')
    s = ""
    while s != None: # loop until end of file is reached
        s = file.readline()
        # manipulate s how you need

此外,您应该使用上面的内联注释,与现在的方式相比,它使代码更容易阅读。