PPS Unit 6 Notes
PPS Unit 6 Notes
PPS Unit 6 Notes
Therefore, it becomes necessary to store data on permanent storage (the disks) in the form of
files and read whenever necessary, without destroying data.
• Every file is identified by its path that begins from root node or the root folder.
• In windows, C:\ is the root folder but you can also have a path that sarts from other
drives like D:\, E:\, etc.
• The file path is known as pathname.
2
PPS Unit-VI DIT,Pimpri
• In the above figure, C:\ is the root node, it has folder Students, it has sub-folder UG,
which has file BE_Com.docx
• File path is written as:
C:\Students\UG\ BE_Com.docx
3
PPS Unit-VI DIT,Pimpri
B. Binary Files
• Binary file is a file which contains data encoded in binary format.
• This data is mainly used for computer storage or for processing purpose.
• The binary data can be word processing document, images, sound or any
executable program.
• We cannot read binary files easily as the data is in encoded format.
• The text file can be processed sequentially while binary file can be processed
sequentially or randomly depending upon the need.
• Like text files, binary files also put EOF as endmarker.
4
PPS Unit-VI DIT,Pimpri
OR
Explain the utility of open function. Explain any 4 modes of opening a file.
Ans.
• A file is a collection of data stored on secondary storage device like hard disk. So to
read or write data from a file we need to open a file.
• Pyhon provides inbuilt functionality named as open() function.
• This function creates a file object, which will be used to invoke methods associated
with it.
• Syntax:
fileobj=open(file_name [, access_mode])
• here,
5
PPS Unit-VI DIT,Pimpri
✓ file_name is a string value that specifies name of the file that you
want to access.
✓ Access_mode indicates the mode in which the file has to be opened.
ie- read, write, append etc.
• The open function returns a file object. This file object will be used to read, write or
to perform any other operation on the file. It works like a file handle.
Acccess Mode:
✓ Access mode is optional parameter and the default file access mode is read(r).
Sr. Access Purpose/ When to Use
No. Mode
1. r -This is the default mode of opening a file.
-Which opens a file in read only mode.
-File pointer is placed at the beginning of the file.
2. rb -This opens a file in read only mode in binary format.
-File pointer is placed at the beginning of the file.
3. r+ -This opens a file for both reading and wring mode.
-File pointer is placed at the beginning of the file.
4. rb+ -This opens a file for both reading and wring mode in binary format.
-File pointer is placed at the beginning of the file.
5. w -This mode opens a file in writing only.
-If file does not exist new file get created.
- If the file already exist, the contents are overwritten.
6. wb -This mode opens a file in writing only in binary format.
-If file does not exist new file get created.
- If the file already exist, the contents are overwritten.
7. w+ -This mode opens a file in both writing and reading.
-If file does not exist new file get created.
- If the file already exist, the contents are overwritten.
8. wb+ -This mode opens a file in both writing and reading in binary format.
-If file does not exist new file get created.
-If the file already exist, the contents are overwritten.
9. a -This mode opens a file in appending mode.
-File pointer is placed at the end of the file.
-if file does not exist, it creates new file.
10. ab -This mode opens a file in appending mode in binary format.
-File pointer is placed at the end of the file.
-if file does not exist, it creates new file.
11. a+ This mode opens a file for reading and appending mode.
-File pointer is placed at the end of the file.
-if file does not exist, it creates new file.
12. ab+ This mode opens a file for reading and appending mode in binary
format.
-File pointer is placed at the end of the file.
-if file does not exist, it creates new file.
6
PPS Unit-VI DIT,Pimpri
Q6. With the help of an example, explain any 3 attributes of file objects.
Ans.
• Python has many inbuilt function and methods to manipulate files.
• To operate a file first we need to open a file using open() function. Once a file
successfully opened, a file object is returned.
• This file object can be used to access different types of information related to that
file.
• This information can be obtained by reading values of specific attributes of the file.
• File has a following file attributes
1. Fileobj.closed :
✓ This attribute returns the True value if the file is closed.
✓ And returns False if it is not closed.
2. Fileobj.mode :
✓ This attribute returns the access mode with which file has been
opened.
3. Fileobj.name :
✓ This Attribute returns the name of the opend file.
• Example:
Output:
Name of the file is: file.txt
Is file closed: false
Mode of opened file is: wb
OR
• Once file object is closed, you cannot read/write file using that object.
• Syntax:
fileobj.close()
• Program to show the use of open() and close() function
fileobj=open("file1.txt","w")
print("File is closed: ", fileobj.closed)
print("File is now being closed ")
fileobj.close()
print("File is closed: ", fileobj.closed)
Output:
File is closed: False
File is now being closed
File is closed: True
• If you have used the same object_name for other file, the previous file object is
closed.
• But as a good programming habit, we should explicitly close the objects which we
have opened.
• The close() function frees up system resources such as file descriptors, file locks, etc,
that are associated with the files.
• There is an upper limit for a program to open number of files.
• If the limit exceeds then program may crash or perform unexpected operations. To
avoid this we should close the unneeded objects.
• If you didn’t closed the file object, python has garbage collector to clean up
unreferenced objects.
• But still it is our responsibility to close the file and release the resources consumed
by it.
8
PPS Unit-VI DIT,Pimpri
OR
fileobj=open("file1.txt","w")
fileobj.write("Hello All, Hope you enjoying Python")
fileobj.close()
print("Data written to the file..")
Output:
Data written to the file..
• File1.txt has been created and content are written to the file.
2. writelines() method:
• This method is used to write a list of strings to a file.
fileobj=open("file1.txt","w")
lines=["Hello world\n", "Welcome to Python\n", "Enjoy\n"]
fileobj.writelines(lines)
fileobj.close()
9
PPS Unit-VI DIT,Pimpri
fileobj=open("file1.txt","r")
print(fileobj.read())
print("Data written to the file..")
Output:
Hello world
Welcome to Python
Enjoy
OR
fileobj=open("file1.txt","a")
fileobj.write("\nHello world \nWelcome to Python\n")
fileobj.close()
print("Data appended to the file..")
Output:
Data appended to the file..
10
PPS Unit-VI DIT,Pimpri
• If you open the file in append mode and if the file is not exist then new file is created
and data writing will begin from start.
Q10. Write a short note on different methods to read data from a file.
OR
file=open(“File1.txt”,”r”)
print(file.read(10))
file.close()
➢ Note that if you try to open a file for reading that does not exist, then you will get an
error as given below-
file1=open(“file2.txt”,”r”)
print(file2.read())
Example:-
Consider file name is File1.txt and program is to read its contents using the
readline() method. The following are the contents of the file-
11
PPS Unit-VI DIT,Pimpri
#File1.txt
Hello All,
Happy Reading
Program code-
file=open(“File1.txt”,”r”)
print(“First Line:”,file.readline())
print(“Second Line:”,file.readline())
print(“Third Line:”,file.readline())
file.close()
➢ After reading a line from the file using the readline() method, the control
automatically passes to the next line. That is why, when we call the readline() again,
the next line in the file is returned.
➢ The readlines() method is used to read all the lines in the file.
➢ Program to demonstrate readlines() function
file=open(“File1.txt”,”r”)
print(file.readlines())
file.close()
12
PPS Unit-VI DIT,Pimpri
OR
Hello World
Program 1:
print(line)
Output:
Hello World
Program 2:
file=open(“file1.txt”,”rb”)
for line in file:
print(line)
print(“Let’s check if the file is closed:”,file.close())
Output:
Hello World
➢ In the first code (Program 1), the file is opened using with keyword. After the file is
used in the for loop, it is automatically closed as soon as the block of code
comprising of the for loop is over.
13
PPS Unit-VI DIT,Pimpri
➢ But when the file is opened without the with keyword, it is not closed
automatically. We need to explicitly close the file after using it.
➢ Advantage of with keyword:
o The file is properly closed after it is used even if an error occurs during read
or write operation or even when we forget to explicitly close the file.
Output:
[‘Hello’, ‘World’, ‘Welcome’, ‘to’, ‘the’, ‘world’, ‘of’ ,‘Python ‘,‘Programming’]
Output:
[‘Hello World’, ‘Welcome to the world of Python Programming’]
14
PPS Unit-VI DIT,Pimpri
• Python has various methods in the os module that help programmers to work
with directories.
• These methods allow users to create, remove, and change directories.
1. mkdir()
• The mkdir() method of the os module is used to create directories in the current
directory.
• The method takes the name of the directory (the one to be created) as an
argument.
• The syntax of mkdir() is:
os.mkdir(“new_dir_name”)
• Program to create a new directory New Dir in the current directory.
import os
os.mkdir(“New Dir”)
print(“Directory Created”)
• Just check the contents of C:\python34 directory. You will find a new directory
name New Dir
2. getcwd()
• The getcwd() method is used to display the current working directory(cwd).
• All files and folders whose path does not exist in the root folder are assumed to
be present in the current directory. So to know your cwd is quite important at
times and for this getcwd() method is used.
• The syntax of getcwd() is:
os.getcwd()
• Program to display a current working directory(cwd).
import os
print(“Current Working Directory: ”, os.getcwd())
OUTPUT
Current Working Directory: C:\Python34
3. chdir()
• The chdir() method is used to change the current directory.
• The method takes the name of the directory which you want to make the current
directory as an argument.
• The syntax of chdir() is:
os.chdir(“dir_name”)
• Program that changes the current directory to our newly created directory --
New Dir
import os
print(“Current Working Directory: ”, os.getcwd())
15
PPS Unit-VI DIT,Pimpri
os.chdir(“New_Dir”)
print(“After chdir, the current directory is now..... ”, end=‘ ’)
print(os.getcwd())
OUTPUT
Current Working Directory: C:\Python34
After chdir, the current directory is now.....C:\Python34\New Dir
• An error message will be displayed if you try to change to a directory that does
not exist.
4. rmdir()
• The rmdir() method is used to remove or delete a directory.
• For this, it accepts the name of the directory to be deleted as an argument.
• However, before removing a directory, it should be absolutely empty and all the
contents in it should be removed.
• The syntax of remove() method is:
os.rmdir(“dir_name”)
• Program to demonstrate the use of rmdir() method
import os
os.rmdir(“New_Dir”)
print(“Directory Deleted.... ”)
OUTPUT
Directory Deleted....
• The code given above will remove our newly created directory—New Dir.
In case, the specified directory is not in the current directory, you should always
specify the complete path of the directory as otherwise the method should search
for that directory in the current directory only.
• Just check the C:\Python34 folder, the New Dir no longer exists in it. If you try
to delete a non-empty directory, then you will get OSError:[WinError 145] The
directory is not empty
• If you still want to delete the non-empty directory, use the rmtree() method
defined in the shutil module as shown below:
import shutil
shutil.rmtree(“Dir1”)
5. os.path.join()
• In Windows, path names are written using backslash ( \ ) but in Unix, Linux, OS
X and other operating system they are specified using the forward slash
character.
16
PPS Unit-VI DIT,Pimpri
• Python os module has a join() method . When you pass a string value of files
and folder names that makes up the path, the os.path.join() method will return a
string with a file path that has correct path separators.
• Program that uses os.path.join() method to form a valid file path
import os
print(os.path.join(“c:”, “students”, “under graduate”, “Btech.docx”))
OUTPUT
c:\students\under graduate\Btech.docx
• The above code is executed on Windows, therefore, the output has backward
slashes. If the same code was run on another operating system(like Linux), you
would have got forward slashes.
• We can use the join() method to form the file path and then pass the file path as
an argument to open(). We first open the file in write mode to write some text in
it, close the file, and the again open to read its content. The program to print the
absolute path of a file using os.path.jon is given below:
import os
path= “d:\\=”
filename= “First.txt”
abs_path=os.path.join(path,filname)
print(“ABSOLUTE FILE PATH=”,abc_path)
file=open(abs_path,”w”)
file.write(“Hello”)
file.close()
file=fopen(abs_path,”r”)
print(file.read())
OUTPUT
ABSOLUTE FILE PATH=d:\First.txt
Hello
6. makedirs()
• The makedirs() methods is used to create more than one folder.
• For example, if you pass string C:\Python34\Dir1\Dir2\Dir3 as an argument to
make makedirs() method, the Python will create folder Dir1 in Python34 folder,
Dir2 in Dir1 folder, and Dir3 in Dir2 folder.
• For example:
import os
os.makedirs(C:\\Python34\\Dir1\Dir2\\Dir3”)
17
PPS Unit-VI DIT,Pimpri
OUTPUT
os.path.dirname( \”C: \\Python \\Chapters \\First Draft \\Strings.docx \”)=
C: \Python \Chapters \First Draft
19
PPS Unit-VI DIT,Pimpri
OUTPUT
os.path.listdir(\”C:\\Python34”)=[‘Dir1’,’DLLs’,’Doc’,’File1.txt’,’include’,
’Lib’,’libs’,’python.exe’ ]
OUTPUT
os.path. isfile (\”C:\\Python34\Try.py\”)= False
os.path. isfile (\”C:\\Python34\Try.py\”)=True
OUTPUT
os.path. isdir (\”C:\\Python34\Try.py\”)= False
os.path. isdir (\”C:\\Python34\Try.py\”)=True
20
PPS Unit-VI DIT,Pimpri
6.7 Dictionaries
Q15. Explain creating a dictionary. How to access, add, modify and delete items in
dictionary.
Ans.
Dictionary
• Dictionary is a data type in python.
• It is unordered collection of items.
• Dictionary is a data structure which stores elements as key: value pairs.
Key: unique, immutable of type strings, & case sensitive.
Value: Can be any data type, can be duplicated(repeated)
• Each key is separated from its value by a colon (:). Consecutive key: value pairs
are separated by commas (,).
• The entire items in a dictionary are enclosed in curly brackets {}.
Syntax:
Dictionary_name = {key1:value1, key2:value2, … }
Example:
dict1 = {1:’PPS’, 2:’PHY’}
print(dict1)
• Creation of Dictionary
• The syntax to create an empty dictionary can be given as:
Dict = { }
Example1:
Dict = { }
print(Dict)
OUTPUT:
{}
Example2:
Dict = {1: "PPS", 2: "PHY"}
print(Dict)
OUTPUT:
{1: 'PPS', 2: 'PHY'}
print(Dict[1])
OUTPUT:
PPS
• Note that if you try to access an item with a key, which is not specified in
dictionary, a KeyError is generated.
Example
Dict = {1: "PPS", 2: "PHY"}
Dict[3] = "M-I"
print(Dict)
OUTPUT :
{1: 'PPS', 2: 'PHY', 3: 'M-I'}
Example:
Dict = {1: "PPS", 2: "PHY", 3: "SME"}
del Dict[2]
print(Dict)
Output:
{1: 'PPS', 3: 'SME'}
22
PPS Unit-VI DIT,Pimpri
Operations on Description
Dictionary: Method
clear() Remove all items from the dictionary.
copy() Return a shallow copy of the dictionary.
items() Return a new view of the dictionary's items
(key, value).
keys() Return a new view of the dictionary's keys.
values() Return a new view of the dictionary's values
23