Chapter 2
Chapter 2
Introduction to Files
• A file is a named location on a secondary storage media like hard disk, pen drive where data
are permanently stored for later access.
• Each program is stored on the secondary device as a file.
• Without files, the output is stored temporarily in RAM. If a new program is run, previous
program goes out of RAM.
• Thus, storage in files allows us to store and retrieve the data according to requirements
of the programmer.
Text File:
• A text file can be understood as a sequence of characters consisting of alphabets, numbers
and other special symbols.
• Files with extensions like .txt, .py, .csv, etc. are some examples of text files.
• Content in the file are stored in sequence of bytes consisting of Os and Is that represent
ASCII value of characters.
• So, while opening a text file, the text editor translates each ASCII value and shows us the
equivalent character.
• For example, the ASCII value 65 will be displayed by a text editor as the letter 'A΄
Binary File:
• The type of files which stores information in the same format as it is held in memory. Stores
information in stream of bytes which does not represent the ASCII values of characters
• Stores data such as image, audio, video, compressed versions of other files, executable files,
etc. These files are not human readable. Thus, trying to open a binary file using a text editor
will show some garbage values.
• Even a single bit change can corrupt the file and make it unreadable to the
supporting application
A text file is a file that stores information in the A binary file is a file that stores the information
form of a stream of ASCII or Unicode in the form of a stream of bytes.
characters.
In text files, each line of text is terminated with In a binary file, there is no delimiter for a line
a special character known as EOL (End of Line) and no character translations occur here.
character.
Files with extensions like .txt, .py, .csvetc are Files with extensions like .jpg, .pdf etc are some
some examples of text files. examples of binary files.
File Modes:
It specifies the type of operation performed after opening the file. Ex: read, write etc
Path: It is defined as sequence of directory names which gives the hierarchy to access a particular
file. It is of two types:
i) Absolute Path: If location of file is specified from root directory.
Ex: C:\\Users\\Desktop\\Demo\\a.txt
ii) Relative Path: If location of file is specified from current working directory. No need to give full
path
Ex: if cwd is C:\\Users\\Desktop . Then relative path to text file is a.txt.
Syntax:
file_object = open("filename", "filemode")
Examples: f = open("myfile.txt") opens the file in read mode.
File pointer is at the beginning. Optional to specify'r mode
f = open("myfile.txt", "w") opens file in Science file in write only mode.
The file_object has certain attributes that tells us basic information about the file, such as:
• <file.closed> returns true if the file is closed and false otherwise.
• <file.mode> returns the access mode in which the file was opened.
• <file.name> returns the name of the file.
File Attributes:
fileobject.closed
True if file is closed
fileobject.mode
The access_mode is an optional argument that represents the mode in which the file has to
be accessed by the program
Output:
The file successfully opened
Output:
The file successfully opened
write() method:
• This function is used to insert string data onto an external file.
• It returns the number of characters being written on single execution.
• If data is in different format, it needs to be converted to string using str()
Syntax: file_object.write(string)
Program:
f = open('C:/Users/sunil/Videos/welcome.txt',mode = 'w')
f.write('SHIKSHANASIRI ACADEMY – PUC SCIENCE & COMMERCE COACHING')
print("data added successfully")
f.close()
writelines() method:
• writelines() function is used to write multiple strings to a file in the form object like lists,
tuple, etc.
• Unlike write(), the writelines() method does not return the number of characters written in
the file.
Syntax: file_object.writelines(LIST/TUPLE)
Program:
f = open('C:/Users/sunil/Videos/welcome.txt',mode = 'w')
f.writelines(['SHIKSHANASIRI ACADEMY.','Learn python, java and C++ \n', 'SSLC - PUC Coaching
Classes\n'])
print("data added successfully")
f.close()
read():
This function is used to read 'n' bytes of data from an existing file.
Syntax: fileobject.read(n)
If no argument or a negative number is specified in read(), the entire file content is read
Program:
f = open('C:/Users/sunil/Videos/welcome.txt', "r")
print(f.read())
f.close()
Output:
SHIKSHANASIRI ACADEMY. Learn python, java and C++
readline(n)): optional
This function is used to read one line of input at a time ending with \n from an existing file.
It can also be used to read a specified number (n) of bytes of data from a file.
Syntax: fileobject.readline(n) //n is optional
If no argument or a negative number is specified in read(), the entire line is read.
Program:
f = open('C:/Users/sunil/Videos/welcome.txt', "r")
print(f.readline(21))
f.close()
Output:
SHIKSHANASIRI ACADEMY
readlines():
This function is used to read all lines from a text file and return the result in the form of list.
Syntax: fileobject.readlines()
Program:
f = open('C:/Users/sunil/Videos/welcome.txt', "r")
print(f.readlines())
f.close()
Output:
['SHIKSHANASIRI ACADEMY.\n', 'Learn python, java and C++ \n', 'SSLC - PUC Coaching
Classes\n']
Programming Example
f = open('C:/Users/sunil/Videos/welcome.txt', "r")
d = f.readlines()
for line in d:
words=line.split()
print(words)
f.close()
Output:
['SHIKSHANASIRI', 'ACADEMY.']
Program:
f = open('C:/Users/sunil/Videos/welcome.txt', "r")
d = f.readlines()
for line in d:
words=line.splitlines()
print(words)
f.close()
Output:
['SHIKSHANASIRI ACADEMY.']
['Learn python, java and C++ ']
['SSLC - PUC Coaching Classes']
str=fileobject.read()
print(str)
print("Initially, the position of the fi le object is: ",fi leobject. tell())
fileobject.seek(0)
print("Now the fi le object is at the beginning of the fi le: ",fileobject.tell())
fileobject.seek(10)
print("We are moving to 10th byte position from the beginning of file")
print("The position of the fi le object is at", fi leobject.tell())
str=fileobject.read()
print(str)
• If file is opened in write mode, existing data is vanished and file object is at beginning of file.
• If opened in append mode, existing data is retained and new data will be added to end of
file.
• If file doesn't exist, it is newly created in both cases.
• Traversing is the process of reading text line by line.
Program: To create a text file and write data in it
# program to create a text file and add data
fileobject=open("practice.txt","w+")
while True:
data= input("Enter data to save in the text file: ")
fileobject.write(data)
ans=input("Do you wish to enter more data?(y/n): ")
if ans=='n': break
fileobject.close()
fileobject = open("practice.txt","r+")
str = fileobject.readline()
while str:
print(str)
str = fileobject.readline()
fileobject.close()
Output:
I am interested to learn about Computer Science. Python is easy to learn
fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
line= input("Enter a sentence ")
fileobject.write(line)
fileobject.write('\n')
choice=input("Do you wish to enter more data? (y/n): ")
if choice in ('n','N'): break
print("The byte position of file object is ",fileobject.tell())
fileobject.seek(0) #places file object at beginning of file
print()
print("READING DATA FROM THE FILE")
str=fileobject.read()
print(str)
fileobject.close()
Output:
RESTART: Path_to_file\Program2-5.py
WRITING DATA IN THE FILE
Enter a sentence I am a student of class XII
Do you wish to enter more data? (y/n): y
Enter a sentence my school contact number is 4390xxx8
Do you wish to enter more data? (y/n): n
The byte position of file object is 67
2) load(): used to read data from binary file (.dat file). It raises EOF Error when when you reach end
of file. Thus we must handle the exception
Syntax: variable = pickle.load(<fileobject>)
Program: Unpickling data in Python
import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
pass
bfile.close()