-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完
你的問題是什麼?你有什麼問題?? – eyllanesc
究竟是什麼問題? – Mureinik
你能添加什麼樣的錯誤嗎?你也可以添加你的代碼被破壞的地方嗎? –