Professional Documents
Culture Documents
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:
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).
2
The write() method does not add a newline character ('\n') to the end of the string
This method writes the list of strings(each string in the list terminated by a newline) into a
file.
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
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()
*The write() method writes a string.The writelines() method writes a list into file.
4
*The read() and readline() methods returns string . The readlines() method returns list
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
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))
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.
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.
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()
7
8