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"
以写入文件(以及我们将在此处跳过的其他一些)。接下来可以调用文件对象的函数。两个最常用的函数是read
和write
。write
函数将字符串添加到文件的末尾。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()