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
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 as– file.txt
Run the above python program First time we get – Output
Run the above python program second time – Output
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.randrange(1,5) – It gives the random value from one – five excluding ending index 5. only takes 1-4 random values.
- 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.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(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.
For Artificial intelligence click here