簡體   English   中英

Python:讀取文件的各個元素

[英]Python: Reading individual elements of a file

我試圖讀取文件的各個元素。 在此示例中,每行的第一個元素是字典的鍵。 接下來的五個元素將是列表形式中所述鍵的對應值。

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 out。

另一種方式:

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似乎#Max - 一個鍵有兩個含義,是學生的名字還是參數的名字? 可能更好地分開它們。

去年我的任務類似於此。

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

此外,您應該使用上面的內聯注釋,與現在的方式相比,它使代碼更容易閱讀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM