2017-05-25 6 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ブロックはこれをオープンファイルエラーとして報告しています。

関連する問題