Text File - write() Function


☞ This function takes argument as a string.

☞ For storing numeric value, we must convert it into a string.

☞ For storing data with end of line character, we must add '\n' character to the end of string.

Example 1 :

#writing single line or word on a text file 

def writing_data():
    f = open("demo.txt","w")
    s=input("Enter something : ")
    f.write(s)      #writing on a text file
    f.close()

writing_data()  #calling a function 

Example 2 :

#writing multiple lines on a text file 

def writing_data():
    f = open("demo.txt","w")
    while True:
        s=input("Enter something : ")
        f.write(s + '\n')      #writing on a text file
        choice = input("Do you wish to continue [y\n] : ")
        if choice == 'n' or choice == 'N':
            break
    f.close()

writing_data()  #calling a function