如何在python中打开文件?

时间:2017-05-25 21:40:02

标签: python python-3.x

我试图编写一个代码,将学生姓名和保存到文件中,但我在打开文件时遇到问题。

以下是代码段。

students = []

def get_students_titlecase():
    students_titlecase = []
    for student in students:
        students_titlecase.append(student["name"].title())
    return students_titlecase


def print_students_titlecase():
    students_titlecase = get_students_titlecase()
    print (students_titlecase)


def add_student(name, student_id):
    student = {"name": name , "student_id": student_id}
    students.append(student)


def save_file(student):
    try:
        f = open("students.txt", "a")
        f.write(student + "\n")
        f.close()
    except Exception:
        print("couldn't open the file")


def read_file():
    try:
        f = open("students.txt", "r")
        for student in f.readlines():
            add_student(student)
        f.close()
    except Exception:
        print("couldn't read file")


read_file()
print_students_titlecase()

student_name = input("Enter the student name: ")
student_id = input("Enter the student_id: ")

add_student(student_name, student_id)
save_file(students)

输出: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/arunyantrapragada/PycharmProjects/FirstProg/function.py [] 输入学生姓名:thomas

输入student_id:456

无法打开文件

处理完成,退出代码为0

1 个答案:

答案 0 :(得分:1)

这就是try / catch块通常不明智的原因。您的错误不是文件无法打开,而是此行引发了错误:

f.write(student + "\n")

+不会附加字典(student)和字符串(\n)。您的try / catch块将此报告为打开文件错误。