TEXT FILE
File:- A file is a collection of related data
DATA FILES:- They are of two types
1. Text Files:-Stores information in ASCII characters.
2. Binary Files:- Stores information in the same format which the information is held
in memory.
OPENING AND CLOSING OF FILE
1. Open():- This unction takes two parameters; filename, and mode. open( ) function
returns a file object
2. Close():- It function is used to close a file.
FILES MODES
Text file Binary File Mode Description
mode
‘r’ ‘rb’ Read - Default mode . Opens a file for
reading,displays error if the file does not exist.
‘w’ ‘wb’ Write - Opens a file for writing, creates the file if it
does not exist
‘a’ ‘ab’ Append - Opens a file for appending, creates the file
if it does not exist
‘r+’ ‘rb+’ Read and Write-File must exist, otherwise error is
raised.
w+’ ‘wb+’ Read and Write :- File is created if does not exist.
‘a+’ ‘ab+’ Read and write-Append new data
Reading the data from a file:
read( ) : reads n bytes. if no n is specified, reads the entire file.
readline( ) : Reads a line. if n is specified, reads n bytes.
readlines( ): Reads all lines and returns a list.
Write data to a file:
write( ): Write string to a file.
writelines( ): Write content of list into files
EXAMPLES OF TEXT FILES
1. Define count vowels( ):- To count number of vowels present in file
"xyz.txt"
def countvowels( ):
f=open("xyz.txt" , "r")
s=f.read( )
c=0
for z in s:
if z in "aeiouAEIOU":
c=c+1
print(c)
2. Define countdo( ):- To count how many times word " Do " , " Do " , " do
" , " dO " is present in file " DO.txt "
f=open("DO.txt" , "r")
s=f.read( )
s=s.split( )
c=0
for z in s:
if z in ["DO" , "Do" ,"do" , "dO"]:
c=c+1
print(c)
3. Define revtext( ):- To display those words in reverse order that are
starting with "A" or "a'
def revtext( ):
f=open("rev.txt" , "r")
s=f.read( )
s=s.split( )
for z in s:
if z[0] in ["A" , "a"]:
print(z[-1: : -1])
4. Define display ( ):- To display those line whose length is more then 5
def display( ):
f=open("country.txt" , "r")
s=f.readlines( )
for z in s:
if len(z) > 5:
print(z)
5. Define display ( ):- To display those lines starting with “I” or “I”
def display( ):
f=open("country.txt" , "r")
s=f.readlines( )
for z in s:
if z[0] in ["I" , "i"]:
print(z)