File Handling.ipynb - Colab
File Handling.ipynb - Colab
ipynb - Colab
1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.
2. readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more
than one line, even if n exceeds the length of the line.
3. readlines() : Reads all the lines and return them as each line a string element in a list.
file1 = open("myfile.txt","r+")
file1.seek(0)
https://colab.research.google.com/drive/1nSG9GLCUuwfH4zuka5_ii3K4TiNYy47j#printMode=true 1/3
11/26/24, 11:07 AM File Handling.ipynb - Colab
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print("Output of Readlines after appending")
print(file1.readlines())
print()
file1.close()
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print("Output of Readlines after writing")
print(file1.readlines())
print()
file1.close()
https://colab.research.google.com/drive/1nSG9GLCUuwfH4zuka5_ii3K4TiNYy47j#printMode=true 2/3
11/26/24, 11:07 AM File Handling.ipynb - Colab
https://colab.research.google.com/drive/1nSG9GLCUuwfH4zuka5_ii3K4TiNYy47j#printMode=true 3/3