Unit 4
Unit 4
(Marks:- 14)
Syllabus
Files :
• File path, Types of files, Opening and Closing files, Reading and Writing files. File
Positions, Renaming and deleting files.
Directory Methods:
Dictionaries:
• 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)
1
Programming and Problem Solving by Prof. Pritish P. Bhale
What is Need of File Handling ?
2
Programming and Problem Solving by Prof. Pritish P. Bhale
Types of files
Types of files
3
Programming and Problem Solving by Prof. Pritish P. Bhale
Types of files
1. Text File
• Typically ending in.txt, these files contain data i.e. characters or strings in a
readable format for humans to access.
• Any text editor can be used to edit the plain text that they contain.
• Text files can be handled in Python utilizing modes like a for appending, w for
writing, and r for reading.
1.Absolute path:
• It always begins with the root folder.
• The absolute path includes the complete directory list required to locate the file.
• An absolute path specifies the location of the file relative to the root directory or it
contains the complete location of the file or directory.
• Example: C:/users/Dell/docs/Div_D.txt
5
Programming and Problem Solving by Prof. Pritish P. Bhale
File Path
2.Relative path:
• It is relative to the program's current working directory
• Relative paths are related to the current working directory.
6
Programming and Problem Solving by Prof. Pritish P. Bhale
File Path
7
Programming and Problem Solving by Prof. Pritish P. Bhale
File Path
8
Programming and Problem Solving by Prof. Pritish P. Bhale
File Handling
• File handling in Python involves
interacting with files on your computer
to read data from them or write data
to them.
9
Programming and Problem Solving by Prof. Pritish P. Bhale
File Handling
• Here is a list of some commonly used file-handling functions in Python.
Function Description
Syntax:
• x = open (file_name, access_mode)
Where,
• file_name = The name of the file that you want to open
• access_mode = read, write, append.
For Example:
• Suppose we have a file named file1.txt.
• To open this file, we can use the open() function.
file1 = open("file1.txt")
• Here, we have created a file object named file1. Now, we can use this object to work with files.11
Programming and Problem Solving by Prof. Pritish P. Bhale
Opening file
File Access Modes:
• ‘x’ : This mode creates a new file but will return an error if the file already exists.
• ‘r’ : This mode indicate that file will be open for reading only.
• ‘w’ : This mode indicate that file will be open for writing only. This will erase or
overwrite on previous content. If file containing containing that name does not exists,
it will create a new one.
• ‘a’ : This mode indicate that the output of that program will be append to the
previous output of that file.
• ‘r+’ : This mode indicate that file will be open for both reading and writing.
Programming and Problem Solving by Prof. Pritish P. Bhale
12
Opening file
1.Creating a new file:
• To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exists.
13
Programming and Problem Solving by Prof. Pritish P. Bhale
Reading files
• The read() method is used in Python for reading the file data.
• To read the file, we need to open it in read mode.
• Reading a file in Python involves opening the file in a mode that allows for
reading, and then using various methods to extract the data from the file.
• Pass file path and access mode to the open(file_path, access_mode) function.
• It returns the file object. This object is used to read or write the file according to
the access mode.
• The Pointer is at the start, so we can proceed writing from start of the file.
• Access mode represents the purpose of opening the file.
• For example, r is for reading and w is for writing
14
Programming and Problem Solving by Prof. Pritish P. Bhale
Reading files
• Python provides several methods to read data from a file −
1) read() Method:
• For example,
• Suppose we have a file named file_1.txt.
• File_1.txt has following data stored in it.
Python is easy…!!!
15
Programming and Problem Solving by Prof. Pritish P. Bhale
Reading files
1) read() Method: Output:
• In the above example, the code file_1.read() reads the content of the
file and stores it in the read_content variable i.e. file1.
16
Programming and Problem Solving by Prof. Pritish P. Bhale
Writing files
• To write to a Python file, we need to open it in write mode using the ’w’ mode.
• 1. If a file already exists, it truncates the existing content and places the
filehandle at the beginning of the file. A new file is created if the mentioned file
doesn’t exist.
• 2. If you want to add content at the end of the file, use the access mode a to
open a file in append mode
17
Programming and Problem Solving by Prof. Pritish P. Bhale
Writing files
• Suppose we have a file named file2.txt. Output:
• Let's write to this file. Programming is Fun
Programming for beginners
# open the file2.txt in write mode
file2 = open('file2.txt', 'w')
• When we run the above code, we will see the specified content inside the file.
18
Programming and Problem Solving by Prof. Pritish P. Bhale
Closing files
Syntax :
fileobject.close()
19
Programming and Problem Solving by Prof. Pritish P. Bhale
Closing files
Example :
f = open("File_1.txt.", "r")
print(f.read())
f.close()
Output :
Note-
(Here, content of File_1.txt will be saved . And all the data will
be saved and finally file will be closed)
20
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
• As we know, by using the read() function we can read the content of the file.
• What if we want to read the file from a specific position or find out from where
the reading begins? Python’s seek() and tell() functions come in handy here.
• In Python, file positions refer to the current location of the file pointer within an
open file.
• This file pointer indicates where the next read or write operation will take place.
• These operations work in binary and text files, but the position is measured in
bytes.
21
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
• A file position may be covered with help of 2 functions:
File Positions
1. Seek() 2. Tell()
function function
22
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
23
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
Syntax:
file.seek(offset, whence)
24
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
Example: Output:
25
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
Syntax:
file_object.tell()
26
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
Example1: Output:
In the above example, As we know for „r‟ i.e. read mode pointer always
works from beginning. So Output shows “0”
27
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
Example2: Output:
In the above example, As we know for „a‟ i.e. append mode pointer always
works from the ending. So Output shows “19”
28
Programming and Problem Solving by Prof. Pritish P. Bhale
Renaming and Deleting Files in Python
• In Python, you can rename and delete files using built-in functions from
the os module.
• Python's OS module supports a variety of file system interaction operations, such
as creating, renaming, and removing files and directories.
• These operations are important when managing files within a file system.
import os
File 'oldfile.txt' renamed to 'newfile.txt' successfully.
Syntax:
os.remove(file_name)
Here,
• This function accepts the name of the file as a parameter which needs to be
deleted.
31
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
Example: Output:
# File to be deleted
file_to_delete = "file_to_delete.txt"
32
Programming and Problem Solving by Prof. Pritish P. Bhale
What is Directory?
• When software is required to manage a massive number of files, we prefer
organizing them by sorting code into different “folders”.
• This makes handling numerous files hassle-free.
• A directory in Python is a folder consists group of files and subdirectories.
• Here, directory inside a directory is known as a subdirectory.
• We use the os module in Python, that allows you to perform various operations on
directories.
• These operations include creating new directories, navigating through existing
directories, listing directory contents, changing the current working directory, and
removing directories.
33
Programming and Problem Solving by Prof. Pritish P. Bhale
Directory Methods
• Python provides the os module for interacting with directory.
• Key methods / operations for working with directories include
• (Make directory)
1. os.mkdir() • to create a new directory
• (Remove directory)
2. os.rmdir() • to remove an empty directory
• (List directory)
4. os.listdir() • to list files and subdirectories within a path
• (Rename directory)
5. os.rename() • to rename the current working directory.
Programming and Problem Solving by Prof. Pritish P. Bhale
34
Directory Methods
1. To create new directory:
• We can create a new directory using the os.mkdir() method.
• We have to pass the name of the newly created directory inside round bracket.
• This method creates a new directory within the CWD by default if no path is
mentioned.
• To create a new directory somewhere else, we must specify the path, which must
contain forward slashes and not backward ones.
Syntax:
os.mkdir(“Directory_1")
35
Programming and Problem Solving by Prof. Pritish P. Bhale
Directory Methods
1. To create new directory: Output:
Example:
Directory created successfully
import os
36
Programming and Problem Solving by Prof. Pritish P. Bhale
Directory Methods
2. To remove directory:
• You can remove an empty directory in Python using the os.rmdir() method.
• If the directory contains files or other directories, you can use shutil.rmtree()
method to delete it recursively.
Example: Example:
Now let's use rmdir() to delete an empty directory, In order to remove a non-empty directory, we can
use the rmtree() method inside the shutil module.
import os
import shutil
# delete the empty directory "mydir"
os.rmdir("mydir") # delete “Directory_1" directory and all of its contents
shutil.rmtree("mydir")
37
Programming and Problem Solving by Prof. Pritish P. Bhale
Directory Methods
3. To Get Current Directory:
• We can get the present working directory using the getcwd() method of the os
module.
• This method returns the current working directory in the form of a string. For
example,
Example: Output:
C:\Program Files\main.py
import os
print(os.getcwd())
38
Programming and Problem Solving by Prof. Pritish P. Bhale
Directory Methods
4. To List Directories and Files:
• To list files in a directory, you can use the os.listdir() function.
• This will return a list of filenames present in the specified directory.. For example,
Example: Output:
['$RECYCLE.BIN',
os.listdir('G:\\') 'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']
39
Programming and Problem Solving by Prof. Pritish P. Bhale
Directory Methods
5. To Renaming a Directory:
• The rename() method can rename a directory or a file.
• For renaming any directory or file, rename() takes in two basic arguments:
the old name as the first argument
Output:
the new name as the second argument.
['$RECYCLE.BIN',
Example: 'Movies',
import os 'Music',
'Photos',
# rename a directory 'Series',
os.rename('test','new_one') 'System Volume Information']
os.listdir()
['new_one']
• Here, 'test' directory is renamed to 'new_one' using the rename()
method. Programming and Problem Solving by Prof. Pritish P. Bhale
40
Dictionary
• A Python dictionary is a collection of items, similar to lists and tuples.
• Dictionary is one of the four built-in data structures in Python used to store data in
key-value pairs.
• A key works as a unique identifier for an element and an attribute to locate the
data in the memory. A value is the data related to that key.
• Values can be of any data type, but keys are immutable, so we can change them to
only numbers, strings, or tuples.
• Although dictionaries store information, such as definitions and words, they can be
used for various other purposes.
• As dictionaries are mutable, we can’t change them once created.
• Also, they are unordered, which means the items in a dictionary are not stored in
any specific order.
• Syntax:
my_dic = {'key1' : 'value1', 'key2' : 'value2', .....,'key_n': 'value_n'}
41
Programming and Problem Solving by Prof. Pritish P. Bhale
Dictionary Methods
1. Create a
Dictionary
5. Find 2. Access
Dictionary Dictionary
Length Items
Dictionary
Methods
4. Change 3. Remove
Dictionary Dictionary
Items Items
42
Programming and Problem Solving by Prof. Pritish P. Bhale
Dictionary
1. Create a Dictionary:
• We create a dictionary by placing key: value pairs inside curly brackets {}, separated by
commas. For example,
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}
• Output:
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}
# printing the dictionary
print(country_capitals)
• Note: We can also use the get() method to access dictionary items.
43
Programming and Problem Solving by Prof. Pritish P. Bhale
Dictionary
2. Access Dictionary Items:
• We can access the value of a dictionary item by placing the key inside square
brackets[].
• For example,
• Output:
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'Italy': 'Rome'}
44
Programming and Problem Solving by Prof. Pritish P. Bhale
Dictionary
3. Remove Dictionary Items
• We can use the del statement to remove an element from a dictionary.
• For example,
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
} • Output:
{'Canada': 'Ottawa'}
# delete item having "Germany" key
del country_capitals["Germany"]
print(country_capitals)
• Note: We can also use the pop() method to remove an item from a dictionary.
45
Programming and Problem Solving by Prof. Pritish P. Bhale
Dictionary
4. Change Dictionary Items:
• Python dictionaries are mutable (changeable). We can change the value of a dictionary element by
referring to its key.
• For example,
country_capitals = {
"Germany": "Berlin",
"Italy": "Naples",
"England": "London" • Output:
} {'Germany': 'Berlin', 'Italy': 'Rome', 'England': 'London'}
print(country_capitals)
• Note: We can also use the update() method to add or change dictionary items.
46
Programming and Problem Solving by Prof. Pritish P. Bhale
Dictionary
5. Find Dictionary Length:
• We can find the length of a dictionary by using the len() function.
• For example,
countries = {}
47
Programming and Problem Solving by Prof. Pritish P. Bhale