Unit VI File Handling and Dictionaries (07 HRS)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Unit VI File Handling and Dictionaries (07 Hrs)

File path, types of files, opening –closing files, reading and writing files,
Dictionary method.

Dictionaries- creating, assessing, adding and updating values.


Case Study: Study design, features, and use of any recent, popular and efficient
system developed using Python. (This topic is to be excluded for theory
examination)
File Handling in Python
A file is collection of data. Python too supports file handling and allows users to
handle files i.e., to read and write files, along with many other file handling
options, to operate on files.
The concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, but alike other concepts of Python,
this concept here is also easy and short.
Working of open() function: Before performing any operation on the file like reading or
writing, first, we have to open that file. For this, we should use Python’s inbuilt function open()
but at the time of opening, we have to specify the mode, which represents the purpose of the
opening file.

f = open(filename, mode)

following mode is supported:


1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data then it
will be overridden.

3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
Creating a file using write() mode

# Python code to create a file

file = open('pps.txt','w')

file.write("Hello")

file.write("Welcome")

file.close()

The close() command terminates all the resources in use


Working of read() mode

There is more than one way to read a file in Python. If you need to extract a string
that contains all characters in the file then we can use file.read().

# Python code to illustrate read() mode


file = open("pps.txt", "r")
print(file.read())

file.close()
Another way to read a file is to call a certain number of characters like in the
following code. The interpreter will read the first two characters of stored data and
return it as a string:

# Python code to illustrate read() mode character wise

file = open("pps.txt", "r")

print(file.read(2))

file.close()
Working of append() mode

# Python code to illustrate append() mode

file = open('pps.txt','a')

file.write("This is last line")

file.close()
One must keep in mind that the mode argument is not mandatory. If not
passed, then Python will assume it to be “ r ” by default.
PPS UNIT-6 FILE HANDLING AND DICTIONARY (Questions and Answers)

Q.what are files. Why do we need them?


Answer: Files and Need of files
1. A file is collection of data stored on a secondary storage device like hard disk.
2. When program is being executed, its data is stored in RAM
3. RAM can accessed faster by CPU, but RAM is volatile/ not permanent storage
4. If you need data in future then you need to store data on permanent storage in files.
5. Files stored in name locations on storage media.
6. To use file first open file, read or write it and then finally close it.
7. File is used because real life applications involve large amount of data
Types of Files in Python
1. Text File
2. Binary File

1. Text File
● Text file store the data in the form of characters.
● Text file are used to store characters or strings.
● Usually we can use text files to store character data
● eg: abc.txt

2. Binary File
● Binary file store entire data in the form of bytes.
● Binary file can be used to store text, image, audio and video.
● Usually we can use binary files to store binary data like images,video files, audio files
etc
Q.What is Directory? Discuss some directory method present in os module. Give
Example. Answer :
-Directory is collection similar or different types of files. os module provides various methods
to create, remove and change directory.

Directory Methods in os Module


1. mkdir() method
2. getcwd( ) method
3. chdir( ) method
4. rmdir( ) method
5. listdir() method
1. mkdir() method- It is used to create new directory in current directory.
Syntax for mkdir() method-
os.mkdir(“name of directory”)

Example Program to create new directory


import os
os.mkdir('mydirectory')
print('directory created')

2. getcwd( ) method- This method display the current working directory (cwd).
Syntax for getcwd() method-
os.getcwd()
Example Program to display current working directory
import os
print(os.getcwd()) #home
3. chdir( ) method-
It is used to change the current directory.
Syntax for chdir() method-
os.chdir('directoryname')

Example Program to change directory


import os
os.chdir('mydirectory')
print(os.getcwd()) # mydirectory

4. rmdir( ) method-
it is used to remove or delete directory.
Syntax for rmdir() method-
os.rmdir('directoryname')

Example Program to remove directory


import os
os.rmdir('mydirectory')
print('directory removed')
5.listdir() method

listdir() method in python is used to get the list of all files and directories in
the specified directory.

# Example Program to list directory and file

import os
print(os.listdir())
Q.Differentiate between absolute path and relative path.
Q.Explain rename() and remove() method of os module.

Os module in python is used to perform file processing operations like rename and delete file. To
use these methods from os module, first import os module in python program.
rename() method
It takes two arguments current filename and new file name
syntax to rename- os.rename(oldfilename,newfilename)
Example to rename file

import os
os.rename('file1.txt','file2.txt')
print('file rename successfully')
remove() method
it is used to delete file.
It takes one argument as file name to delete.
Syntax to delete file-
os.remove(filename)
Example to delete file

import os
os.remove('file1.txt')
print('file deleted successfully')
One must keep in mind that the mode argument is not mandatory. If not passed,
then Python will assume it to be “ r ” by default. Let’s look at this program and try
to analyze how the read mode works:

# a file named "geek", will be opened with the reading


mode. file = open('geek.txt', 'r')
# This will print every line one by one in the file
for each in file:

print (each)
The open command will open the file in the read mode and the for loop will
print each line present in the file.
Thanks

You might also like