To see how to handle the files and its operations in python3.
Python has a built-in function open() to open a file.
It is used to read or modify the file accordingly.
r------Opens a file for reading only(default)
w------Opens a file for writing only
rb-----Open a file for reading only in binary format
rb+---Opens a file for both reading and writing in binary format
wb----Opens a file for writing only in binary format
wb+---Opens a file for both writing and reading in binary format
When we are done with operations to the file, we need to properly close the file.
File will be close by using Python close().
#read a file using loop and readlines()
#os package for detect the file directory
import os
os.chdir(‘/home/soft23/soft23/Sathish
/Pythonfiles’)
list=[]
for line in open(‘read_it.txt’,’r’).readlines():
list.append(line)
#slicing
list=list[0:10]
str1=”.join(list)
print(“—–Before writing the file—–“)
print(str1)
#writing the same file with new content
import os
os.chdir(‘/home/soft23/soft23/Sathish
/Pythonfiles’)
fo = open(“read_it.txt”, “w”)
fo.write( “Python is a great language.\nIts very easy to learn.\nPython has easy syntax\nIts very easy to learn”)
print(“File writting is heppening…”)
#close the file
fo.close()
#After writing the file
import os
os.chdir(‘/home/soft23/soft23/Sathish
/Pythonfiles’)
list=[]
for line in open(‘read_it.txt’,’r’).readlines():
list.append(line)
#slicing
list=list[0:10]
str1=”.join(list)
print(“—–After writing the file—–“)
print(str1)
(new_list1)