Appending to File

Overview

- First Way

    - Opening the File in Append Mode

    - Adding new data to the file

    - Closing the File

    - Opening the File in Read Mode to check if new data is added

    - Closing the File

- Second way (open with)

    - Opening the File & Adding new data to it

    - Reading the File

First Way

Opening the File in Append Mode

In [21]:
students = open("student.csv","a")

Adding a new data to the file

- using \n for adding to a new line 
In [13]:
students.write("\n1, will, 29 , male")
Out[13]:
19

Closing the File

In [14]:
students.close()

Reading the File

- Checking if new data is added
In [15]:
students = open("student.csv","r")

print(students.read())
1, Sarah, 29 , female
2, John, 30, male
3, Jack, 28, male
4, Anna, 27, female
1, will, 29 , male

Closing the File

In [14]:
students.close()

Second Way

Adding new data to the File

- using \n for adding to a new line 
In [18]:
with open("student.csv", "a") as students:
    
    student = students.write("\n6, rose, 29 , female")
    
    print(student)
21

Reading the file

In [22]:
with open("student.csv", "r") as students:
     
    for student in students:
        
        print(student)
1, Sarah, 29 , female

2, John, 30, male

3, Jack, 28, male

4, Anna, 27, female

5, will, 29 , male

6, rose, 29 , female