Computer Science Chapter
Computer Science Chapter
The data files are the files that store data pertaining to a specific
application. It is a bunch of files store on some storage devices. Like hard
disk, flash device, CD, DVD etc. The data files can be stored in two ways.
1) Text File 2) Binary Files
Opening and Closing Files :- In Python you need to open a file in a specific mode as
per the file manipulation task you want to perform. The most base task for
manipulation of files are adding, deleting or modifying data in a file. Which in turn
include any one or combination of following.
Opening File :- In data file handling Python, the first you need to open file using
open() function.
Syntax :- File objects are
<file_object_name>=open(<file_name>) used to read
<file_object_name>=open(<file_name>,<mode>) and write data
to file on disk.
Example
myFile1 = open(‘taxes.txt’)
Syntax:-
<file handle>.close()
<file object>.close()
myFile.close()
Reading and Writing:- Python provide many functions for reading and
writing the open files
Reading From File
Sno Method Syntax Description
1 read() <fo>.read([n]) *read n byte if n is specified otherwise
read the entire file.
*Return the read byte in the form of a
string.
fileobj=object.open(‘info.txt’,’r’)
info=fileobj.read(15) Reads 15
print(info) characters from
info.txt file in
the form of
string.
Reading From File
Sno Method Syntax Description
2 readline() <fo>.readline([n]) *Reads a line of input; if n is specified
reads at most n bytes.
*Return the read byte in the form of
string ending with \n character of
return a blank string if no more bytes
are left for reading in the file.
fileobj=object.open(‘info.txt’,’r’)
info=fileobj.readline() Read one line
print(info)
info=fileobj.readline(5) Read 5 bytes
print(info)
Reading From File
Sno Method Syntax Description
3 readlines() <fo>.readlines() *Reads all lines in the form of list. Line 1
store index 0 and line 2 index 1 and so
on.
fileobj=object.open(‘info.txt’,’r’)
info=fileobj.readlines()
print(info)
Read all lines
Info is list type
Reading From File
Output
Reading From File
Output
Reading From File
Output
Reading From File
Output
Reading From File
Output
Reading From File
Output
Writing into File
Sno Method Syntax Description
1 write() <fo>.write(st) *Write string st into the file
representing by <file handler>.
2 writelines() <fo>.writelines(L) *Write all string in list L as line into
the file representing by
<file handler> .
File object File name File Mode