跳转到内容

Python 2.6 非程序员教程/文件 I/O

来自维基教科书,开放书籍,为开放世界

这是一个简单的文件 I/O(输入/输出)示例

# Write a file
out_file = open("test.txt", "w")
out_file.write("This Text is going to out file\nLook at it and see!")
out_file.close()

# Read a file
in_file = open("test.txt", "r")
text = in_file.read()
in_file.close()

print text

输出和文件 test.txt 的内容是

This Text is going to out file
Look at it and see!

注意它在您运行程序的目录中创建了一个名为 test.txt 的文件。字符串中的 \n 指示 Python 在该位置插入一个换行符

文件 I/O 的概览是

  • 使用 open 函数获取文件对象。
  • 读取或写入文件对象(取决于打开方式)。
  • 关闭它。

第一步是获取文件对象。方法是使用 open 函数。格式为 file_object = open(filename, mode),其中 file_object 是用于放置文件对象的变量,filename 是包含文件名 的字符串,而 mode"r" 用于读取文件或 "w" 用于写入文件(以及其他一些我们将跳过的选项)。接下来可以调用文件对象的函数。两个最常见的函数是 readwritewrite 函数在文件末尾添加一个字符串。read 函数读取文件中的下一个内容并将其作为字符串返回。如果没有给出参数,它将返回整个文件(如示例中所示)。

现在,这里是我们之前编写的电话号码程序的新版本

def print_numbers(numbers):
    print "Telephone Numbers:"
    for x in numbers.keys():
        print "Name:", x, "\tNumber:", numbers[x]
    print

def add_number(numbers, name, number):
    numbers[name] = number

def lookup_number(numbers, name):
    if name in numbers:
        return "The number is " + numbers[name]
    else:
        return name + " was not found"

def remove_number(numbers, name):
    if name in numbers:
        del numbers[name]
    else:
        print name," was not found"

def load_numbers(numbers, filename):
    in_file = open(filename, "r")
    for in_line in in_file:
        in_line = in_line.rstrip('\n') #Eliminate end of line or enter        
        name, number = in_line.split(",")
        numbers[name] = number
    in_file.close()

def save_numbers(numbers, filename):
    out_file = open(filename, "w")
    for x in numbers.keys():
        out_file.write(x + "," + numbers[x] + "\n")
    out_file.close()

def print_menu():
    print '1. Print Phone Numbers'
    print '2. Add a Phone Number'
    print '3. Remove a Phone Number'
    print '4. Lookup a Phone Number'
    print '5. Load numbers'
    print '6. Save numbers'
    print '7. Quit'
    print

phone_list = {}
menu_choice = 0
print_menu()
while True:
    menu_choice = input("Type in a number (1-7): ")
    if menu_choice == 1:
        print_numbers(phone_list)
    elif menu_choice == 2:
        print "Add Name and Number"
        name = raw_input("Name: ")
        phone = raw_input("Number: ")
        add_number(phone_list, name, phone)
    elif menu_choice == 3:
        print "Remove Name and Number"
        name = raw_input("Name: ")
        remove_number(phone_list, name)
    elif menu_choice == 4:
        print "Lookup Number"
        name = raw_input("Name: ")
        print lookup_number(phone_list, name)
    elif menu_choice == 5:
        filename = raw_input("Filename to load: ")
        load_numbers(phone_list, filename)
    elif menu_choice == 6:
        filename = raw_input("Filename to save: ")
        save_numbers(phone_list, filename)
    elif menu_choice == 7:
        break
    else:
        print_menu()

print "Goodbye"

注意它现在包括保存和加载文件。以下是我运行它两次的输出

1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Load numbers
6. Save numbers
7. Quit

Type in a number (1-7): 2
Add Name and Number
Name: Jill
Number: 1234
Type in a number (1-7): 2
Add Name and Number
Name: Fred
Number: 4321
Type in a number (1-7): 1
Telephone Numbers:
Name: Jill     Number: 1234
Name: Fred     Number: 4321

Type in a number (1-7): 6
Filename to save: numbers.txt
Type in a number (1-7): 7
Goodbye
1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Load numbers
6. Save numbers
7. Quit

Type in a number (1-7): 5
Filename to load: numbers.txt
Type in a number (1-7): 1
Telephone Numbers:
Name: Jill     Number: 1234
Name: Fred     Number: 4321

Type in a number (1-7): 7
Goodbye

此程序的新部分是

def load_numbers(numbers, filename):
    in_file = open(filename, "r")
    while True:
        in_line = in_file.readline()
        if not in_line:
            break
        in_line = in_line[:-1]
        name, number = in_line.split(",")
        numbers[name] = number
    in_file.close()
def save_numbers(numbers, filename):
    out_file = open(filename, "w")
    for x in numbers.keys():
        out_file.write(x + "," + numbers[x] + "\n")
    out_file.close()

首先,我们将查看程序的保存部分。它首先使用命令 open(filename, "w") 创建一个文件对象。接下来,它遍历所有电话号码并使用命令 out_file.write(x + "," + numbers[x] + "\n") 为每个电话号码创建一个行。这将写入一行,包含姓名、逗号、号码,并在其后跟一个换行符。

加载部分稍微复杂一些。它首先获取一个文件对象。然后,它使用 while True: 循环持续循环,直到遇到 break 语句。接下来,它使用行 in_line = in_file.readline() 获取一行。当遇到文件末尾时,readline 函数将返回一个空字符串。if 语句检查此情况并在发生这种情况时从 while 循环中 break。当然,如果 readline 函数没有在行尾返回换行符,那么就无法判断空字符串是空行还是文件末尾,因此换行符保留在 readline 返回的内容中。因此,我们必须去除换行符。行 in_line = in_line[:-1] 通过删除最后一个字符来实现这一点。接下来,行 name, number = in_line.split(",") 在逗号处将行拆分为姓名和号码。然后将其添加到 numbers 字典中。

现在修改第 字典 节中提供的成绩程序,使其使用文件 I/O 来记录学生信息。

解答

现在修改第 字典 节中提供的成绩程序,使其使用文件 I/O 来记录学生信息。

assignments = ['hw ch 1', 'hw ch 2', 'quiz   ', 'hw ch 3', 'test']
students = { }

def load_grades(gradesfile):
    inputfile = open(gradesfile, "r")
    grades = [ ]
    while True:
        student_and_grade = inputfile.readline()
        student_and_grade = student_and_grade[:-1]
        if not student_and_grade:
            break
        else:
            studentname, studentgrades = student_and_grade.split(",")
            studentgrades = studentgrades.split(" ")
            students[studentname] = studentgrades
    inputfile.close()
    print "Grades loaded."

def save_grades(gradesfile):
    outputfile = open(gradesfile, "w")
    for i in students.keys():
        outputfile.write(i + ",")
        for x in students[i]:
            outputfile.write(x + ",") #added missing comma
        outputfile.write("\n")
    outputfile.close()
    print "Grades saved."

def print_menu():
    print "1. Add student"
    print "2. Remove student"
    print "3. Load grades"
    print "4. Record grade"
    print "5. Print grades"
    print "6. Save grades"
    print "7. Print Menu"
    print "9. Quit"

def print_all_grades():
    keys = students.keys()
    if keys:
        keys.sort()
        print '\t',
        for i in range(len(assignments)):
            print assignments[i], '\t',
        print
        for x in keys:
            print x, '\t',
            grades = students[x]
            print_grades(grades)
    else:
        print "There are no grades to print."

def print_grades(grades):
    for i in range(len(grades)):
        print grades[i], '\t',
    print

print_menu()
menu_choice = 0
while menu_choice != 9:
    print
    menu_choice = input("Menu Choice: ")
    if menu_choice == 1:
        name = raw_input("Student to add: ")
        students[name] = [0] * len(assignments)
    elif menu_choice == 2:
        name = raw_input("Student to remove: ")
        if name in students:
            del students[name]
        else:
            print "Student:", name, "not found"
    elif menu_choice == 3:
        gradesfile = raw_input("Load grades from which file? ")
        load_grades(gradesfile)
    elif menu_choice == 4:
        print "Record Grade"
        name = raw_input("Student: ")
        if name in students:
            grades = students[name]
            print "Type in the number of the grade to record"
            print "Type a 0 (zero) to exit"
            for i in range(len(assignments)):
                print i + 1, assignments[i], '\t',
            print
            print_grades(grades)
            which = 1234
            while which != -1:
                which = input("Change which Grade: ")
                which = which - 1
                if 0 <= which < len(grades):
                    grade = raw_input("Grade: ") # Change from input() to raw_input() to avoid an error when saving
                    grades[which] = grade
                elif which != -1:
                    print "Invalid Grade Number"
        else:
            print "Student not found"
    elif menu_choice == 5:
        print_all_grades()
    elif menu_choice == 6:
        gradesfile = raw_input("Save grades to which file? ")
        save_grades(gradesfile)
    elif menu_choice != 9:
        print_menu()


华夏公益教科书