Python Tutorial, Theory of Evolution

How to read and write a text file in python?

You have already seen in the python that these following access_mode used to access text file in python

Read Only (‘r’) : Read Only ‘r’ is used only when you want read text file.

Read and Write (‘r+’) : Read and Write (‘r+’ ) work simultaneously to access the read and write txt file.

Append Only (‘a’) : Append Only ‘a’ is only used for appending the txt file.

Write Only (‘w’) : Write Only ‘w’ is only used when you only want read text file from any location.

Append and Read (‘a+’) : Append and Read (‘a+’ ) where you want simultaneously append & read ‘a+’ is used

Program – How to read and write text file simultaneously

Code :



with open("C:\\ClassStudies_Python\\file.txt","r+") as myfile:   #file location, access_method both read and write simulateously

    print(myfile.read())                    #print the read file(text file)

    myfile.write("I am fine, Thankyou! ")   #after reading,write the file on it.

myfile.close()                              #used for close the file



Create text file named asfile.txt

Run the above python program First time we getOutput

Run the above python program second timeOutput

Now, you can see the magic Text file value is change at every run because first read the text file and then write on it. That’s why changes happens at every run.

Now, come to know the concept of Random values

Random keyword in python

First you should import random

  • random.randint(1,5) – It gives the random value from 1-5 including starting index one and ending index 5.

random.randint(1,5)
Out[28]: 5

  • random.randrange(1,5) – It gives the random value from one – five excluding ending index 5. only takes 1-4 random values.

random.randrange(1,5)
Out[12]: 1

  • random. random() – It gives the output between the range 0-1. Any value which belongs to two more than 0 and less than 1.

random.random()
Out[13]: 0.44922384406943106

  • random.randrange(1,10,2) – It takes random values which is an odd number, starting from index 1 and ending with index 10 and the gap between these number is 2. Suppose the start number is 1 and then the gap is 2 , next number is 3, similarly run and gives random odd value till the 10 integers.

random.randrange(1,10,2)
Out[14]: 9

  • random.randrange(2,11,2) – It takes random values which is even number, starting from index 2 and ending with index 10 and the gap between these number is 2. Suppose the start number is 2 and then the gap is 2, next number is 4, similarly run and gives random odd value till the 10 integers.

random.randrange(2,11,2)
Out[16]: 6

For Artificial intelligence click here

Leave a Comment

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

Scroll to Top