You are on page 1of 8

Files

File:

The file is a data structure used for storing data that are permanent. Files are traditional way
of storing data.

Files can store data in binary format or text format. The binary file is not human readable
abut occupies less memory. The text files are human readable but occupy much space than
binary file

File operations:

The operations on file include:

 Creates a file and open a file and places the file pointer in the beginning or end based
on the modes
 Reading, writing, appending and manipulations can be done on a file
 File is closed once all the operations on a file are completed

File modes:

Modes Description

r Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.

rb Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.

r+ Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.

rb+ Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.

w Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.

wb Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.

1
w+ Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.

wb+ Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.

a Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.

ab Opens a file for appending in binary format. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.

a+ Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist,
it creates a new file for reading and writing.

ab+ Opens a file for both appending and reading in binary format. The file pointer is
at the end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.

File methods :

Creation of files:

Open()

The open function creates a memory space and returns a file object, and is most commonly
used with two arguments: open(filename, mode).

Reading and Writing Files:


The file object provides a set of access methods to make our lives easier. We would see how
to use read() and write() methods to read and write files.

The write() Method


The write() method writes any string to an open file. It is important to note that Python
strings can have binary data and not just text.

2
The write() method does not add a newline character ('\n') to the end of the string

The Writelines() Method:

This method writes the list of strings(each string in the list terminated by a newline) into a
file.

The read() Method


The read() method reads a string from an open file. It is important to note that Python strings
can have binary data apart from text data. The read method reads the whole file and returns
the whole contents as a string.

The read(count) Method

This method reads the count of characters from the file

The readline() Method

This method reads the file line by line

The Readlines() Method :

This method returns the whole file contents where the lines of file are stored as a data item
in the list and the list is returned

Closing the file:


The close() Method
The close() method of a file object flushes any unwritten information and closes the file
object, after which no more writing can be done.
Example 1: Writing a string into a file using write() Method
fd = open('file1.txt','w')
inp = input()
fd.write(inp)
fd.close()

Example 2: Writing a list of strings into a file using writelines() Method


fd = open('file2.txt','w')
n = int(input())
l = [ input() + '\n' for i in range(n)]
fd.writelines(l)
fd.close()

3
Example 3: Writing lines into a file using write () Method
fd = open('file1.txt','w')
con = 1
while ( con == 1 ):
inp = input()
inp = inp + "\n"
fd.write(inp)
con = int(input("continue enter 1\t:"))
fd.close()

Example 4: Appending contents to a file


fd = open('file2.txt','a')
n = int(input())
l = [ input() + '\n' for i in range(n)]
fd.writelines(l)
fd.close()

*The write() method writes a string.The writelines() method writes a list into file.

Example 5:Reading the whole file using read() Method


fd = open('file2.txt','r')
s = fd.read()
print(s)
fd.close()

Example 6:Reading a single line using readline() Method


fd = open('file2.txt','r')
s = fd.readline()
print(s)
fd.close()

Example 7:Reading a lines of file using readlines() Method


fd = open('file2.txt','r')
l = fd.readlines()
print(l)
fd.close()

Example 8:Reading a line by line from file using for loop


fd = open('file1.txt','r')
for s in fd:
print ( s )
fd.close()

4
*The read() and readline() methods returns string . The readlines() method returns list

Example 9.1: Finding the length of a file


import os
print(os.path.getsize('file2.txt'))
fd.close()

Example 9.2: Finding length of file


fd = open('file2.txt','r')
s = fd.read()
print(len(s))
fd.close()

Program1: Program to find char count , word count and line count of a file
import re
def countChars( file ):
cc = len(file.read())
file.close()
return cc

def countLines( file ):


cl = len(file.readlines())
file.close()
return cl

def countWords( file ):


r = re.compile("\W+")
s = file.read()
l = r.split(s)
print (l)
cw = len(l)
file.close()
return cw - 1

fd = open('file1.txt','r')
print ( "Number of chars is\t:",countChars(fd))
fd = open('file1.txt','r')
print ( "Number of Lines is\t:",countLines(fd))
fd = open('file1.txt','r')
print ( "Number of words is\t:",countWords(fd))

Program 2: To display of pangrams in a file

Create a file “pangrams.txt” and store the following lines


Zing, dwarf jocks vex lymph Nymphs blitz quick vex dwarf jog.
Vamp fox held quartz duck just by wing The five boxing wizards jump quickly.
Quizzical twins proved my hijack-bug fix
Sympathizing would fix Quaker objectives.

5
Pack my red box with five dozen quality jugs.
The quick brown fox jumped over the lazy dogs.
The lazy major was fixing Cupid’s broken quiver
Vhjhjkhjhjkhjhjhjhjhj
Ereettuiyiu’;k;l,.mnvb

The python code that reads the pangrams.txt and displays only the pangrams
def pang( s ):
s = s.lower()
l = [ ch for ch in s if str.isalpha(ch) ]
s1 = set(l)
if len (s1) == 26:
print (s)
fd = open('pangrams.txt','r')
for line in fd:
pang( line )
fd.close()

The Files are accessed sequentially if files are opened in read or write mode.

Radom access files:


The reading and writing can be done from any place. The file pointer positions have to be
known.
File Positions pointer Methods:
The tell() method tells you the current position within the file; in other words, the next read
or write will occur at that many bytes from the beginning of the file.

The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.

If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of
the file would be taken as the reference position.

Example 10: Accessing the contents of file at random


f='file2.txt'
fd = open(f,'r+')
ch = fd.read(1) #read the first character
print(ch) #print the first character
fd.seek(5) #position the file pointer(FP) to 5th offset
#from the beg(0)
ch = fd.read(1) #read the fifth character
print(ch) #print the fith character
print( fd.tell())#FP points to the next position i.e 6

6
print(fd.read() )#Prints the remaining chars from 6 to eof
print(fd.tell() )#prints the size of the file,FP points to eof
l = fd.tell()-2 # l is 2 bytes from EOF(EOF occupies 2 bytes)
fd.seek(l) #positioning FP to the last char
print(fd.read()) #prints the last character(new line )
l = fd.tell()-3
fd.seek(l) #positioning FP to the last but 1 char
print(fd.read()) #prints the last but one character
fd.close()

Program 3:Reversing the contents of file and stripping of newlines and display on
screen
import os
f='file2.txt'
fd = open(f,'r+')
l = os.path.getsize(f) # returns size of file in bytes
print(l)
for i in range ( l - 2 , -1 , -1 ): #End Of File takes last 2
#bytes
fd.seek(i)
ch = fd.read(1)
if ch != '\n':
print(ch,end='')
fd.close()

Program 4: Changing every upper case to lower case and lower case to upper case
s = 'file2.txt'
fd = open(s,'r+')
fp = fd.tell()
ch = fd.read(1)
while(ch):
if str.isupper(ch):
ch = ch.lower()
else:
ch = ch.upper()
fd.seek( fp)
fd.write(ch)
fp = fd.tell()
ch = fd.read(1)
fd.close()

Program 5: finding size of file using tell()


import os
f='file2.txt'
fd = open(f,'r+')
s =fd.read() #reads the contents of the file until eof
print(s) #prints the contents of file as s
print(fd.tell() ) # file pointer points to end of file, and
# i.e. the size. The size is printed

7
8

You might also like