<<

Std XII Computer Science Handling

Need for a file The supplied through the input statements/functions can be retained as long the programs are executed. When the programs are terminated, the data is lost. The entire data has again to be provided while executing the programs. This process becomes tedious, when certain tasks such as maintaining databases required for students, employees, passengers which need a large amount of data/information. Using a data file, which is a collection of inter related records, can eliminate this limitation. Moreover, the data file is a stream of and is permanently stored in the auxiliary/secondary storage devices such as hard-disk, pen-drive etc.. If there is a need, such file can also be modified,

Types of file in Python In Python, the data files are stored in two different formats viz.  : Such a file stores information in user readable form i.e. ASCII or Unicode character. The text file contains several lines of text in which each line is terminated / delimited by an End-of-Line (EOL) character (Default EOL is a new line character i.e. ‘\n’). Translators are used to or EOL. The text files are the least prone to getting corrupted. As the text files use simple and standard format, they are capable of processing only information in the form of text by using text editors namely Microsoft Notepad , WordPad, which are bundled with Windows and Apple Text Edit, which is included with Mac OS X.  Binary file: Such file stores information in a sequence of bytes or group of eight bits. Binary file doesn’t use EOL as delimiter and the binary file is faster and easier in processing information. The binary files are prone to getting corrupted as a loss of even 1 bit of information may corrupt entire file. Unlike a text file, a binary can be used to store multiple types of data in the same file, such as image, video, and audio data.

Opening the data file It is a process of providing a link between a program and a data file while reading information from a file, writing information into a file or modifying the contents of the file. A file in Python can be opened by using the function (), which is a built-in or a library function. This function returns a file object, known as a handle to maintain reference on the object. The handle is a vital tool in file processing and is assigned with NULL, if the file opened doesn’t exist in the system.

Syntax of open() function

File_object = open( [, access_mode][, buffering])

Distance Learning Programme through E-module by AEES, Mumbai Page 1 of 6

Std XII Computer Science File Handling

where,

 File_object is an identifier used for opening a file and accessing the information.

 filename is an argument/parameter of type string, which holds name of the data file.

 access_mode determines the mode in which the file has to be opened, i.e. read, write or append, etc. It is an optional parameter/ argument . By default, the accessing mode is read-only < ‘r’ >. The following table gives a complete list of possible accessing modes in Python.

 Buffering is an optional parameter/ argument: By default, its value is 0, indicating that no buffering action will happen. If its value is 1, then line buffering will be performed while accessing the file. If its value is larger than 1, then the buffering action will take place as per the buffer size. In the case of a negative value, the system’s default behaviour is considered.

Access Mode Purpose ‘r’ Open a text file for reading, which is also the default mode. ‘w’ Open a text file for writing. If the file already exists, then its contents will be erased due to the overwriting of new data. ‘a’ Open a text file for appending data at the end of the existing file. If the file does not exist, a new file will be created. ‘r+’ Read and write a text file. ‘w+’ Read and write a text file. If the file exists, the new contents will be written over the existing contents. ‘a+’ Read and append a text file. ‘rb’ Read a binary file. ‘wb’ Create a binary file (write) ‘ab’ Append data into binary file. If the file does not exist, a new file will be created. ‘r+b’ or ‘rb+’ Read and write a binary file ‘w+b’ or Read and write a binary file ‘wb+’ ‘a+b’ or ‘ab+’ Read and append binary file

Distance Learning Programme through E-module by AEES, Mumbai Page 2 of 6

Std XII Computer Science File Handling

Closing a file In order to safeguard the data (information) and terminate the link between the file and buffer, the file has to be closed before the program is terminated. The library function () is used for closing a file. However, most of the /interpreters automatically close the file while terminating the program.

Its syntax is

File_object . close()

Where, File_object is used to open file for accessing the information.

Examples for opening and closing files

1. Fp = open(‘INFO.TXT’, ‘r+’) Here, the function open() opens a text file named as INFO.TXT by using file object/ handle ‘Fp’ for reading and writing as indicated by the accessing mode ‘r+’.

2. File = open (‘MOVIE.DAT, ‘a+b’) Here, ‘a+b’ indicates that the binary file ‘MOVIE.DAT’ is opened for reading information from it or appending information into it.

Functions used for processing text files Python supports many input and output functions for accessing a text file. The most commonly used functions are read(), readline(), readlines(), write() and writelines(). read(n) function It is an input function, which reads n bytes from a file and assigns with a string variable. Its syntax is Str_variable = FP.read(n) where, the Str_variable is of the type string and FP is the file object / file handle used for opening the file. To read entire file, its syntax will be

Str_variable = FP.read() readline() function It is an input function, which reads a complete line from a file terminated by the new line character ‘\n’ and assigns with a string variable. Its syntax is Str_variable = FP.readline()

Distance Learning Programme through E-module by AEES, Mumbai Page 3 of 6

Std XII Computer Science File Handling

readlines() function It is an input function, which reads the entire file including new line character and assigns with a string variable. Its syntax is Str_variable = FP.readlines() write(str) function It is an output function, which writes the string ‘str’ into the file. Its syntax is FP.write(str) writelines(estr) function It is an output function, which writes the entire string ‘estr’ consisting of many strings into the file. Its syntax is FP.writelines(estr)

#program to create a file with n names and display those names starting letters with ‘S’ or ‘V’

#To create the file fp=open('NAME.TXT','w') n=int(input('Enter n=')) for i in range(n): name=input('Enter name=') fp.write(name+' ') fp.close()

#To read the file fp=open('NAME.TXT','r') string=fp.read() # Reads complete file words=string.split() # To split string into words print("Names starting with 'S' or 'V' are : ", end=' ') for w in words: if w[0]=='S' or w[0]=='V': print(w,end=' ') fp.close()

OUTPUT Enter n=6 Enter name=Vasanth Enter name=Kriyansh Enter name=Arvind

Distance Learning Programme through E-module by AEES, Mumbai Page 4 of 6

Std XII Computer Science File Handling

Enter name=Vinil Enter name=Swati Enter name=Nirmal Names starting with 'S' or 'V' are : Vasanth Vinil Swati

#Program using functions to create file to write words and # read the file to count words def CreateFile(): fp=open('WORD.TXT','w')

info= input('Enter string = ') fp.write(info) print(info)

fp.close() def ReadFile(): fp=open('WORD.TXT','r')

string=fp.read() words=string.split()

C=0 for w in words: if w=='IS' or w=='TO' or w=='UP': +=1

print("Number of times words IS, TO and UP used : ", C) fp.close()

#_MAIN_

CreateFile() ReadFile()

OUTPUT Enter string = IS AND TO UP TO OR IS AND TO UP TO OR Number of times words IS, TO and UP used : 4

Distance Learning Programme through E-module by AEES, Mumbai Page 5 of 6

Std XII Computer Science File Handling

#program using functions to create file to store lines #and read the file to display lines def CreateFile(): fp=open('LINE.TXT','w')

n = int (input('Enter number of lines = ')) for i in range(n): print("Enter line ", i+1, end=' : ') line = input() fp.write(line +'\n') fp.close() def ReadFile(): fp=open('LINE.TXT','r') Line =fp.readlines() print("Lines starting with A or E : ") for L in Line : if L[0]=='A' or L[0]=='E': print(L) fp.close()

#_MAIN_ CreateFile() ReadFile()

OUTPUT Enter number of lines = 4 Enter line 1 : A clear environment is good for health Enter line 2 : We should take care Enter line 3 : All the schools should take lead Enter line 4 : Everybody should stay in and be safe Lines starting with A or E : A clear environment is good for health All the schools should take lead Everybody should stay in and be safe

Distance Learning Programme through E-module by AEES, Mumbai Page 6 of 6