Python Learning - Section 09 Write File Using Command Prompt

Python Learning - Section 09 Write File Using Command Prompt

           file = open("test.py" , "w")
           file.write("hello")
           file.close()        

You can write a file like this :

w - write

a - append

r - read

This will create the file "text.py" will have one line of text to have multiple lines , use the \n character inside the write function can ,

            f.write("hello world \n")
            f.write("video count \n")        
No alt text provided for this image

To make python add(append) to a file, change the parameter when opening from

           fopen("filename.txt" , "w")        

to,

           fopen("filename.txt" , "a")        

Any line written to the file will then be added to the bottom

No alt text provided for this image
         fobj = open("testfile.txt" , "r")
                print(fobj.readlines())
         fobj.readlines()        

or,

         with open("testfile.txt") as f :
              print(f.readlines())        

To read a file, change the parameter to "r"

use this line to open a file,

            fobj = open("filename.txt" , "r")        

Then you can read the data with

            lines = fobj.readlines()        

Finally, close the file

           fobj.close()        

Write variable to file

                x = [3,4,5,1,3,84,3,2,11]
                file = open("testfile.txt" , "w")
                     for element in x :
                         file.write(str(element) + ",\n")
                file.close()        

To view or add a comment, sign in

More articles by Dananjaya Fernando

Insights from the community

Others also viewed

Explore topics