2017-05-25 89 views
-6

我想写一个代码,需要学生的名字和保存到一个文件,但我得到的问题与打开文件。如何在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) 

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

输入student_id数据:456

无法打开文件

进程退出代码为0完

+1

你的问题是什么?你有什么问题?? – eyllanesc

+0

究竟是什么问题? – Mureinik

+0

你能添加什么样的错误吗?你也可以添加你的代码被破坏的地方吗? –

回答

1

这是try/catch块通常不明智的原因。你的错误不是该文件无法打开,而是这条线被扔了一个错误:

f.write(student + "\n") 

+不追加词典(student)和一个字符串(\n)。你的try/catch块报告这是一个打开的文件错误。