如何在python中打开文件?

2024-06-25 06:52:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个代码,以学生的名字和保存到一个文件,但我有问题打开文件。在

下面是代码片段。在

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)

输出: /库/框架/Python.framework/Versions/3.6/bin/python3.6/Users/arunyantrapragada/PycharmProjects/FirstProg/函数.py [] 输入学生姓名:thomas

输入学生编号:456

无法打开文件

进程结束,退出代码为0


Tags: 文件the代码nameaddidreaddef
1条回答
网友
1楼 · 发布于 2024-06-25 06:52:35

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

f.write(student + "\n")

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

相关问题 更多 >