2017-05-25 93 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塊報告這是一個打開的文件錯誤。