0% found this document useful (0 votes)
8 views

Unit 6 notes

This document provides an overview of file handling and dictionaries in Python, detailing concepts such as file paths, types of files, and methods for reading and writing files. It explains the use of built-in functions like open(), read(), write(), and the attributes of file objects, as well as directory and dictionary methods. Additionally, it includes examples of Python programs for various file operations and dictionary manipulations.

Uploaded by

whatsappupop
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)
8 views

Unit 6 notes

This document provides an overview of file handling and dictionaries in Python, detailing concepts such as file paths, types of files, and methods for reading and writing files. It explains the use of built-in functions like open(), read(), write(), and the attributes of file objects, as well as directory and dictionary methods. Additionally, it includes examples of Python programs for various file operations and dictionary manipulations.

Uploaded by

whatsappupop
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/ 17

Unit-VI

File Handling and Dictionaries


File Path:

Definition: File is a named location on the disk to store information.


 File is basically used to store the information permanently on secondary memory.
 Due to this, even if computer is switched off, the data remains permanently on
secondary memory (hard disk). Hence it is called persistent data structure.
 Every file is located by its path. This path begins at the root folder. In windows it
can C:\,D:\or E:\etc.

The file path is also called as pathname.

Example: C:\myPythonPrograms\displaystrings.py is a pathname. In this path name C:\is


root folder in which subfolder myPythonProgramshas a file called displaystrings.py

The character \used in the pathname is called delimiter.


Concept of Relative and Absolute Path:
 The absolute path is complete path from the root directory.
Example: C:\myPythonPrograms\Strings\displaystrings.py
 The Relative path is a path towards the file from the current working directory.
Example:\Strings\displaystrings.py can be a relative path if you are currently in the
working directory C:\myPythonPrograms

Types of Files
There are two types of files.
1. Text File
2. Binary file

Text File Binary file

Data is present in the form of characters. Data is present in the encoded form.

The plain text is present in the file. The image, audio, or text data can be
present in the file.

It cannot be corrupted easily. Even if single bit is changed then the file
gets corrupted.

It can be opened and read using simple text It cannot read using the text editor like
editor like Notepad Notepad.

It have the extension such as .py or .txt It can have application defined extension.

Opening a File:
In python there is a built in function open() to open a file.
Syntax:
File_object=open(file_name,mode)
Where file_object is used as a handle to the file.
Example:
F=open(“test.txt”)
Here file named test.txt is opened and the file object is in variable F.
We can open the file in text mode or in binary mode. There are various modes of a
file in which it is opened.

Example:
Fo=open(“test.txt”,w) #opens a file in write mode.
Fo=open(“text.txt”,rt) #opens a file for reading in text mode
Write a python program to print the details of the file object.
Fo= open(“test.txt”, “r+”)
print(Fo)
Output:
<_io.TextIOWrapper name='test.txt' mode='rt' encoding='cp1252'>
File object Attributes:
On opening the file successfully, the file object is returned. It is possible to get
different types of information related to file using the attributes associated with the
file object.
These attributes are:
1. fileobj.name: It returns the name of file.
2. fileobj.mode: It returns mode of the file with which the file is opened.
3. fileobj.closed: It returns True if the file is closed otherwise false.

Write a python program to display the values of file object attributes.


fo=open("G:\\test.txt","r+")
print("File Name:",fo.name)
if(fo.closed==True):
print("File is closed")
else:
print("File is open")
print("File mode:",fo.mode)
Output:
File Name: test.txt
File is open
File mode: r+
Closing Files:
 After performing all the file operations, it is necessary to close the file.
 Closing of file is necessary because it frees all the resources that are associated
with file.
Example:
fo=open(“test.txt”,rt)
fo.close() #closing file
Reading Files:
 For reading the file, we must open the file in r mode and we must specify the
correct file name which is to be read.
 The read() method is used for reading the file.
Example:
>>> inf=open("G:\\test.txt","rt")
>>> inf.read()
Output:
'Introduction to File operations.\nReading and Writing file operations in python
are easy to understand.\nwe enjoy it.\nThis line is written to file.\nThis is the last
line of the file.'
 Simple read operation will display the text with \n character.
 Let us close this file and reopen it. Then call read statement inside the print
statement.
>>> inf.close()
>>> inf=open("G:\\test.txt","rt")
>>> print(inf.read())
Output:

Introduction to File operations.


Reading and Writing file operations in python are easy to understand.
we enjoy it.
This line is written to file.
This is the last line of the file.
If we write read() statement inside the print statement. Then the contents will be
displayed in the same manner as they are stored inside the file.
Write a Python program to read the contents of the file named ‘test.txt’.
inf=open("G:\\test.txt","rt")
print(inf.read())
inf.close()
Output:
Introduction to File operations.
Reading and Writing file operations in python are easy to understand.
we enjoy it.
This line is written to file.
This is the last line of the file.
The readline() Method:
 The readline() method allows us to read single line from the file. When file
reaches to the end, it returns an empty string.
Example: Write a python program to read and display first two lines of the text
file.
inf=open("G:\\test.txt","rt")
print(inf.readline())
print(inf.readline())
inf.close()
Output:
Introduction to File operations.
Reading and Writing file operations in python are easy to understand.
The readlines() Method:
 The readlines() method is used display all lines in the file, as a list where each
line is an item in the list.
Example:
inf=open("G:\\test.txt","rt")
print(inf.readlines())
inf.close()
Output:
['Introduction to File operations.\n', 'Reading and Writing file operations in
python are easy to understand.\n', 'we enjoy it.\n', 'This line is written to
file.\n', 'This is the last line of the file.']

Displaying File using Loop:


 This is the most commonly used method of reading the file.
 In this method, the contents of the file are read line by line using for loop.
Example: Write a python program to display the contents of the file using for
loop.
inf=open("G:\\test.txt","rt")
for line in inf:
print(line)
inf.close()
Output:
Introduction to File operations.
Reading and Writing file operations in python are easy to understand.
we enjoy it.
This line is written to file.
This is the last line of the file.
Write a python program to find the line starts with the word “This” from the
following text which is stored in file.
inf=open("G:\\test1.txt","rt")
for line in inf:
line=line.rstrip()
if line.find("This")==-1:
continue
print(line)
Output:
This is a python program.
This is third line of program.
Write a python program to split the text line written in the file into words.
inf=open("G:\\test.txt","rt")
line=inf.readline()
word_list=line.split()
print(word_list)
Output:
['Introduction', 'to', 'File', 'operations.']

Writing Files
 For writing the contents to the file, we must open it in writing mode. Hence we
use ‘w’, or ‘a’, or ‘x’ as a file mode.
 The write method is used to write the contents to the file.
Syntax:
File_object.write(contents)
Example:
fo=open(“G:\\text2.txt”, “wt”)
fo.write(“Introduction to file operations”)
fo.close()
Output:
Open text2.txt file and check whether the contents are written or not
The writelines() method:
 The writelines() method is used to write list of strings to the file.
Example:
fo=open("G:\\text3.txt","wt")
lines=["Welcome to the python programming\n","It is fun\n","Python is
easy\n","But it is powerful programming language."]
fo.writelines(lines)
fo.close()
Output:
Open the file text3.txt, it will display above lines.

Appending the file:


 It means inserting records at the end of the file.
 For appending the file we must open the file in ‘a’ or ‘ab’ mode.
Example:
fo=open("G:\\text3.txt","a")
fo.write("\nPython has a wide scope in future.\n")
fo.close()
Output:
Open the file text3.txt, it will display above line in the existing file.

Write a python program to write n number of lines to the file and display all
these lines as output.
print("How many lines you want to write:")
n=int(input())
outfile=open("G:\\text4.txt","wt")
for i in range(n):
print("Enter the line:")
line=input()
outfile.write("\n"+line)
outfile.close()
print("The contents of the files are ...")
infile=open("G:\\text4.txt","rt")
print(infile.read())
infile.close()
Output:
How many lines you want to write:
3
Enter the line:
This is first line
Enter the line:
This is the second line
Enter the line:
This is third line
The contents of the files are ...
This is first line
This is the second line
This is third line

Write a python program to write the contents in ‘one.txt’ file. Read these
contents and write them to another file named ‘two.txt’.
print("How many lines you want to write:")
n=int(input())
outfile=open("G:\\one.txt","wt")
for i in range(n):
print("Enter the line:")
line=input()
outfile.write("\n"+line)
outfile.close()
infile=open("G:\\one.txt","rt")
outfile=open("G:\\two.txt","wt")
i=0
for i in range(n+1):
line=infile.readline()
outfile.write("\n"+line)
infile.close()
outfile.close()
print("The contents of the files are ...")
infile=open("G:\\two.txt","rt")
print(infile.read())
infile.close()
Output:
How many lines you want to write:
3
Enter the line:
This is first line
Enter the line:
This is second line
Enter the line:
This is third line
The contents of the files are...
This is first line
This is second line
This is third line
File Positions:
Two methods are:
1.seek() Method: It is used to change the file position. It sets the file’s current
position at the offset.
Syntax:
Fileobject.seek(offset[,whence])
Where,
offset: This is the position of the read/write pointer within the file.
whence: This is optional and defaults to 0 which means absolute file positioning,
other values are 1 which means seek relative to the current positions and 2 means seek
relative to the file’s end.
2.tell() Method: The method tell() returns the current position of the file read/write
pointer within the file.
Syntax:
Fileobject.tell()

Example:

inf=open("G:\\text3.txt","rt")
print("\tThe Contents of the files are:")
print(inf.read())
print("\tThe current position is:")
print(inf.tell())#get current position of file
inf.seek(0)#moves the file cursor to the initial position.
print("\tThe current Position is:")
print(inf.tell())#get current position of file
inf.seek(20)
print("\tThe current Position is:")
print(inf.tell())#get current position of file
print("\tThe Contents of the files are:")
print(inf.read())

Output:
The Contents of the files are:
Welcome to the python programming
It is fun
Python is easy
But it is powerful programming language.
Python has a wide scope in future.
The current position is:
140
The current Position is:
0
The current Position is:
20
The Contents of the files are:
n programming
It is fun
Python is easy
But it is powerful programming language.
Python has a wide scope in future.

Directory Methods:
1) Getting current working directory: We use function named getcwd(), which returns
the name of current working directory.
Example:
import os
print(os.getcwd())
Output:
C:\Users\Ganesh\AppData\Local\Programs\Python\Python37-32
2) Displaying all the files and sub-directories inside a directory: We use function
named listdir(), which returns contents of directory.
Example:
import os
print(os.listdir())
Output:
['aa.py', 'add.py', 'assignment_10.py', 'assignment_11.py', 'assignment_12.py',
'assignment_2.py', 'assignment_3.py', 'assignment_4.py', 'assignment_5.py',
'assignment_6.py', 'assignment_7.py', 'assignment_8.py‘]
3) Creating a new Directory:
We can create a new directory using mkdir() method.
Example:
import os
os.mkdir("Mypythonprograms")#create a folder named mypythonprograms
print(os.listdir())#displaying the directory contents
4) Removing the directory or a file:
A file can be deleted using remove() method.
The rmdir() method remove an empty directory.
Example:
import os
os.remove("a1.py")#remove files test1.txt
print(os.listdir())#display the directory contents
os.rmdir("Mypythonprograms")#removes the directory named Mypythonprograms
print(os.listdir())#displays the directory contents

Dictionary Methods:
1. Adding item to dictionary: we can add the item to the dictionary.
>>> a={1:'red',2:'blue',3:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow'}
>>> a[4]='black'
>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow', 4: 'black'}
2. Remove item from dictionary: For removing an item from the dictionary we use
the keyword del.
>>> a={1: 'red', 2: 'blue', 3: 'yellow', 4: 'black'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow', 4: 'black'}
>>> del a[2]
>>> print(a)
{1: 'red', 3: 'yellow', 4: 'black'}

3) Updating the value of the dictionary: we can update the value of the dictionary by
directly assigning the value to corresponding key position.

>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
>>> a[2]='pink'
>>> print(a)
{1: 'red', 2: 'pink', 3: 'black', 4: 'yellow'}

4) Checking length: The len() function gives the number of pairs in the dictionary.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> len(a)
4

Dictionaries and Files:


Using dictionaries we can count the occurrence of the words in the text file.
fh=open("G:\\text3.txt","rt")
d=dict()
for line in fh:
words=line.split()
for i in words:
if i not in d:
d[i]=1
else:
d[i]=d[i]+1
print(d)
Output:
{'Welcome': 1, 'to': 1, 'the': 1, 'python': 1, 'programming': 2, 'It': 1, 'is': 3, 'fun': 1,
'Python': 2, 'easy': 1, 'But': 1, 'it': 1, 'powerful': 1, 'language.': 1, 'has': 1, 'a': 1, 'wide': 1,
'scope': 1, 'in': 1, 'future.': 1}

Write a Program in python to count number of vowels and consonants present in


the text file.
infile=open("G:\\text3.txt","rt")
vowels=set("AEIOUaeiou")
cons=set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")
count_Vowels=0
count_Cons=0
for c in infile.read():
if c in vowels:
count_Vowels=count_Vowels+1
elif c in cons:
count_Cons=count_Cons+1
print("Number of Vowles in a file are:",count_Vowels)
print("Number of consonants in a file are:",count_Cons)
infile.close()
Write a Program in python to count total number of lines in a file.
count=0
infile=open("G:text3.txt","rt")
for line in infile:
word=line.split()
count=count+1
infile.close()
print("Total number of lines in file are:",count)
Output:
Total number of lines in file are: 5

Write a Program in python to count total number of words in a file.


count=0
infile=open("G:text3.txt","rt")
for line in infile:
word=line.split()
count=count+len(word)
infile.close()
print("Total number of words in file are:",count)
Output:
Total number of words in file are: 24

You might also like