Friday, December 22, 2017

Opening,Reading and Writing Files Python

Let's save our data in a file and read from that file again when we re-open our app.
So let's take an example:

Let's take an example:

students =[]

def get_students_titlecase():
       students_titlecase = []
        for student in students:
           students_titlecase .append( student["name"].title())

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name,student_id=1):
        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("Could not save")
       
def read_file():
       try:
             f=open("students.txt","r")
              for student in f.readlines():
                      add_student(student)
                f.close()
         except Exception:
              print("Could not read file")

read_file()
print_students_titlecase()

student_name=input("Enter student name: ")
student_id= input("Enter student ID: ")

add_student(student_name,student_id)
save_file(student_name)

where a= append some text
             r = reading text file

So when you run the program.the output will be something like this

Output:

Could not read file
[]
Enter student name:

No comments: