Monday, 1 August 2016

Tutorial: File Reading and Writing Methods

1)
Create an empty text file.

>>>fo = open("my_file.txt", "w")        # The file is newly created  
>>>fo.close()                                    # Closing file. VERY IMPORTANT!




Now we create an empty file "my_file.txt" with mode "w".


2)  
Write to the file.

Next i am going to write something to this file, for that we have to open the file with "w" write mode ok

>>>fw = open("my_file.txt", "w")     
>>>fw.write("Hai Friends..")                # .write(str)
>>>fw.close()




3)
Read from a file.

Next i am going to read the content from this file and print it on the console, for that open the file with "r" mode

>>>fr = open("my_file.txt", "r")
>>>content = fr.read()                       # .read()
>>>print content
>>>fr.close()