Writing and Reading Information from a File in Python

Writing and Reading Information from a File in Python

 

Writing and Reading Information from a File in Python. in this article i will show  how to read and write file by stepping through the sample python code.

Writing File 

  • Before we are able to write a file , we need to open it
  • So i use the open() python finction to open the file call “employee.txt” by assigning the “w” ehich is a write function
  • And save the result into a Variable myfile

 

>>> myfile=open("employee.txt","w")


  1. Now i will write some info into the file
>>> myfile.write("Mike\nJack")

  1. After you are done , close the file
  2. Open the file again
  3. Use the read() function to read the content inside the file
  4. save what you have read inside a variable
  5. Print out the variable
>>> myfile.close()
>>> myfile=open("employee.txt")
>>> m =myfile.read()
>>> print(m)


Out Put should look like this

Mike
Jackbrian
>>> 

Check out Custom Function in Python here

Leave a Reply

Your email address will not be published. Required fields are marked *

5 + 19 =