0% found this document useful (0 votes)
5 views47 pages

Unit 4

This document covers file handling and directory methods in Python, detailing file types, paths, and operations such as opening, reading, writing, renaming, and deleting files. It explains the importance of file handling for data persistence beyond program execution and introduces key functions like open(), read(), write(), seek(), and tell(). Additionally, it discusses the use of the os module for renaming and deleting files.

Uploaded by

ommishra150905
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views47 pages

Unit 4

This document covers file handling and directory methods in Python, detailing file types, paths, and operations such as opening, reading, writing, renaming, and deleting files. It explains the importance of file handling for data persistence beyond program execution and introduces key functions like open(), read(), write(), seek(), and tell(). Additionally, it discusses the use of the os module for renaming and deleting files.

Uploaded by

ommishra150905
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Unit No. IV - File Handling and Directories.

(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 ?

• As we know there are 2 types of memory.


• i.e. 1) RAM (Primary or Volatile Memory) and
2) Hard drive (Secondary or Non-volatile Memory)
• When a Python program runs on screen or console, the data created or collected during
its execution (like user input, program output, variables, etc.) is stored in temporarily in
memory (RAM).
• Once the program ends or closed, this data is lost permanently, unless we save it.
• To keep data store permanently, we use files to store it(In Hard Drive), so we can retrieve
it whenever we want in future.
• So our program can be stored permanently in hard drive using a “File”

2
Programming and Problem Solving by Prof. Pritish P. Bhale
Types of files

• There are 2 types of files in file handling in python.

Types of files

1.Text File 2.Binary File

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.

2. Binary Files:


• Unlike text files, binary files used to store binary data contain data like pictures,
films, or computer programs that are not readable by humans.
• .bin or.dat are typical extensions for them.
• Python handles similar to text files, binary files with the addition of ab suffix,
such as rb for reading binary files and wb for writing them.
4
Programming and Problem Solving by Prof. Pritish P. Bhale
File Path
• A file path defines the location of a file or folder in the computer system.
• A path is a way to reach the file, containing a combination of directory and folder
names separated by slashes and colons, giving a route to the file in the system.

• There are two ways to specify a file path.

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.

• Example: If our current working directory(CWD) is C:/users/Dell/, then


the relative path to Scaler.txt would be docs/Scaler.txt

• Broadly we can say,


• CWD + relative path = absolute path

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.

• Python provides several built-in


functions and methods for creating,
opening, reading, writing/Adding, and
closing files.

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

open() Used to open a file.


readable() Used to check whether the file can be read or not.

readline() Used to read a single line from the file.

readlines() Used to read all the content in the form of lines.

read() Used to read whole content at a time.


writable() Used to check whether the file is writable or not.

write() Used to write a string to the file.


writelines() Used to write multiple strings at a time.

close() Used to close the file from the program.


10
Programming and Problem Solving by Prof. Pritish P. Bhale
1. Opening file
• A file operation starts with the file opening.
• At first, open the any other File then Python will start the operation.
• File opening is done with the open() function in Python.

 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.

• For e.g. Create a file called "myfile.txt":


Syntax:
f = open("myfile.txt", "x")

• Result: a new empty file is created!

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() − Reads the entire file.


2. readline() − Reads one line at a time.
3. readlines − Reads all lines into a list.

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:

• Now, let's read the content of the file. Python is easy…!!!

# open a file in read mode


file1 = open("file_1.txt” , “r”)

# read the file content


read_content = file1.read()
print(read_content)

• 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')

# write contents to the file2.txt file


file2.write('Programming is Fun.\n')
file2.write('Programming for beginners\n')

• 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

• We can close a file in Python using the close() method.


• Closing a file is an essential step in file handling to ensure that all resources used
by the file are properly released.

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

1. Seek() Function:


• The seek() function in Python is used to move the file cursor to the specified
location.
• When we read a file, the cursor starts at the beginning, but we can move it to a
specific position by passing an arbitrary integer (based on the length of the
content in the file) to the seek() function. For, e.g.

23
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions

1. Seek() Function:

Syntax:
file.seek(offset, whence)

• offset − This is the number of positions to set the pointer to read/write.


• whence − (Optional) It defaults to 0; which means absolute file positioning,
other values are 1 which means seek relative to the current position and 2 means
seek relative to the file's end.

• Suppose we a text file Fille_2.txt having content in it as


This is a test file.

24
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
Example: Output:

f1 = open('File_2','r') is a Test File.


f1.seek(5)
data = f1.read()
print(data)

25
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions

2. Tell() Function:


• Tell() method is used to find the current position of the file cursor (or pointer)
within the file.
• The tell() method returns the current position (in bytes) of the file pointer
within the file.
• This method is mostly used in scenarios where there is a need to determine
whether the file cursor is either at the beginning of the file or the ending.

Syntax:
file_object.tell()

26
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
Example1: Output:

file = open('File_1.txt', ‘r') Content: 0


content = file.tell()
print("Content:", content)
file.close()

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:

file = open('File_1.txt', 'a') Content: 19


content = file.tell()
print("Content:", content)
file.close()

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.

1. Renaming files:


To rename a file in Python, you can use the os.rename() function.
This function takes two arguments: the current filename and the new filename.
Syntax:
os.rename(current_file_name, new_file_name)
Where,
• current_file_name − It is the current name of the file you want to rename.
• new_file_name − It is the new name you want to assign to the file.
29
Programming and Problem Solving by Prof. Pritish P. Bhale
File Positions
Example: Output:

import os
File 'oldfile.txt' renamed to 'newfile.txt' successfully.

# Current file name


current_name = "oldfile.txt"

# New file name


new_name = "newfile.txt"

# Rename the file


os.rename(current_name, new_name)

print(f"File '{current_name}' renamed to '{new_name}' successfully.")


30
Programming and Problem Solving by Prof. Pritish P. Bhale
Renaming and Deleting Files in Python
2. Deleting files:
You can delete a file in Python using the os.remove() function.
This function deletes a file specified by its filename.

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:

import os File 'file_to_delete.txt' deleted successfully.

# File to be deleted
file_to_delete = "file_to_delete.txt"

# Delete the file


os.remove(file_to_delete)

print(f"File '{file_to_delete}' deleted successfully.")

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

• (Get current working directory)


3. os.getcwd() • to get the current working 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")

• Here, we created new directory named as “Directory_1” in CWD.

35
Programming and Problem Solving by Prof. Pritish P. Bhale
Directory Methods
1. To create new directory: Output:
Example:
Directory created successfully
import os

# Create a directory “Directory_1"


os.mkdir("Directory_1")

print ("Directory created successfully")

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())

# Output: C:\Program Files\PyScripter

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,

country_capitals = { "Germany": "Berlin",


"Canada": "Ottawa", }
# add an item with "Italy" as key and "Rome" as its value
country_capitals["Italy"] = "Rome“
print(country_capitals)

• 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'}

# change the value of "Italy" key to "Rome"


country_capitals["Italy"] = "Rome"

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,

country_capitals = {"England": "London", "Italy": "Rome"}

# get dictionary's length


print(len(country_capitals)) # Output: 2

numbers = {10: "ten", 20: "twenty", 30: "thirty"}

# get dictionary's length


print(len(numbers)) # Output: 3

countries = {}

# get dictionary's length


print(len(countries)) # Output: 0

47
Programming and Problem Solving by Prof. Pritish P. Bhale

You might also like