Cara mengimpor nilai ke file teks di Python

students = list() # initialize an accumulator list

with open("stuff2.txt") as infile:
    for line in infile:
        data = line.strip().split(" ")
        # strip removes ending and beginning whitespace e.g. the ending \n and etc
        datadict = {}
        datadict['first'] = data[0]
        datadict['last'] = data[1]
        datadict['grades'] = data[2:]
        students.append(datadict)
        # this can all be done in one line, but it's much clearer this way
# after this, all your students are in `students`, each entry in `students` is a
# dictionary with keys `first`, `last`, and `grades`.

# OUTPUT
with open("newstuff.txt","w") as outfile:
    for student in students:
        outputline = ""
        outputline += student['first']
        outputline += " "
        outputline += student['last']
        outputline += ": "
        outputline += ", ".join(student['grades'])
        # ", ".join(list) gives you a string with every element of list
        # separated by a comma and a space, e.g. ','.join(["1","2","3"]) == "1, 2, 3"
        outputline += "|| average: "
        average = str(sum(map(int,student['grades']))/len(student['grades']))
        # since student['grades'] is a list of strings, and we need to add them, you
        # have to use map(int, student['grades']) to get their int representations.
        # this is equivalent to [int(grade) for grade in student['grades']]
        outputline += average
        outputline += "\n"

        outfile.write(outputline)

        # again, this can be done in one line
        # outfile.write("{0['first']} {0['last']}: {1}||{2}\n".format(
        #              student, ', '.join(student['grades']), sum(map(int,student['grades']))/len(student['grades']))
        # but, again, this is long and unwieldy.
Better Badger