Python
a=open('meera1.txt','w')
print("enter
any text until you press '~' symbol")
#enter
any text
#I
want to enter text into the file until I press '~'
s=input()#it takes string into LHS variable
s
if s!='~':
a.write(s+"\n")
else:
break
a.close()
"""
meera1.txt
rueiorueiorueioureo
rueiorueoiru
"""
#read
the existing file name 'meera1.txt'
a=open('meera1.txt','r')
#read
the file
s=a.read()
print(s)
a.close()
"""
meera1.txt
rueiorueiorueioureo
rueiorueoiru
#append
the text to the existing file name
'meera1.txt'
a=open('meera1.txt','a')
a.write("I'm
santhoshkumar")
##a.append()
a.close()
"""
meera1.txt
rueiorueiorueioureo
rueiorueoiru
I'm
santhoshkumar
"""
import fileinput as fi
#append the text to begining of the file to the existing file name 'meera1.txt'
a='F:\Programs\ESC\meera2.txt'
##a=open('meera2.txt','r+')
for i in fi.FileInput(a,inplace=1):
if 'visakhapatnam' in i:
i=i.rstrip()
i=i.replace(i,i+'Guntur is
containment zone'+'\n')
print(i)
##a.close()
"""
meera2.txt
Dear
Team,
visakhapatnam
guntur
I'm
santhoshkumarGood morning all
After
executing the above code:
meera2.txt
#count
the number of line, words and characters from the existing file
fname=input("enter
filename: ")
if
os.path.isfile(fname): #this condition checks whether the file exits or not
f=open(fname,'r')
else:
print(fname+' does not exist')
sys.exit()
#no
of lines,words and characters
l=w=c=0
#read
line by line
for
i in f:
words=i.split()
l+=1 #it counts no of lines in the file
w=w+len(words)
c=c+len(i)#it counts no of characters in
the file
print("no
of lines=",l)
print("no
of words=",w)
print("no
of chars=",c)
f.close()
"""
enter
filenamemeera2.txt
no
of lines= 20
no
of words= 16
no
of chars= 144
Case2:
enter
filename: meera3.txt
meera3.txt
does not exist
"""
Dear Team,
#using
binary files
#open
the image file in binary mode
f=open('image.png','rb') #exiting image opened, f points to it
a=open('pytlogo.png','wb')#new png file is created, a points to it
#read the binary file and copy into a
bytes=f.read()
a.write(bytes) #copying into pytlogo.png
a.close()
f.close()
Binary files handles the data in the form of bytes. It is used to read,write the text,audio, video files.
To open a existing binary files , use ‘rb’ mode. Representing binary file.
To
read the binary file use read() method.
If
you want to write the binary file use ‘wb’ mode
Related Video: https://youtu.be/EwP28YFF00s
Next: Files with Exception handling