0% found this document useful (0 votes)
77 views14 pages

PPS - NOTES - Unit-6 .

The document discusses file handling in Python including file paths, opening and closing files, reading and writing files, and directories. It defines absolute and relative file paths and describes different file types and modes for opening files. Methods for reading, writing, and directory handling are also covered.

Uploaded by

Shankar Bhosale
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)
77 views14 pages

PPS - NOTES - Unit-6 .

The document discusses file handling in Python including file paths, opening and closing files, reading and writing files, and directories. It defines absolute and relative file paths and describes different file types and modes for opening files. Methods for reading, writing, and directory handling are also covered.

Uploaded by

Shankar Bhosale
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/ 14

Unit VI File Handling and Dictionaries

Files: Introduction, File path, Types of files, Opening and Closing files, Reading and Writing files. Dictionary method.
Dictionaries- creating, assessing, adding and updating values.
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.
 Our to this, even if the computer is switched off, the data remains permanently on secondary memory (hard
disk). Hence it is called persistent data structure.

File Path
A file path defines the location of a file or folder in the computer system. There are two ways to specify a file
path.

1. Absolute path: which always begins with the root directory


2. Relative path: which is relative to the program's current working directory

• 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.
For example C: \ MyPythonPrograms \ displayStrings.py is a pathname. In this path name C:\ is a root folder in
which the sub-folder MyPythonProgram has a file called displayStrings.py
• The character \ used in the pathname is called delimiter.

Concept of Relative and Absolute Path :


o The absolute path is a complete path from the root directory. For example - the path
C: kNlyPythonPrograms \ Strings displayStrings.py is an absolute path using which the file can be located.
o The relative path is a path towards the file from the current working directory.
For example • StringstdisplayStrings.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
1. Text File
 The text ASCII file is a simple file containing collection of characters that are readable to human.
 Various operations that can be performed on text files are — opening the file, reading the file, writing to the
file, appending data to the file.
 The text file deals with the text stream.
 In text file each line contains any number of characters include one or more characters including a special
character that denotes the end of file. Each line of the text have maximum 255 characters.
 When a data is written to the file, each newline character is converted to carriage return/ line feed character.
Similarly when data is read from the file, each carriage return feed character is converted to newline character.
 Each line of data in the text file ends with newline character and each file ends with special character called
EOF (i.e. End of File) character.
(2) Binary File
• Binary file is a file which contains data encoded in binary form.
• This data is mainly used for computer storage or for processing purpose.
• The binary data can be word processing documents, images, sound, spreadsheets, videos, or any other
executable programs.
• We can read text files easily as the contents of text file are ordinary strings but we can not easily read the
binary files as the contents are in encoded form.
• The text file can be processed sequentially while binary files can be processed sequentially or randomly
depending upon the need.
• Like text files, binary files also put EOF as an endmarker.

Difference between Text File and Binary File



Sr. Text File
No. Binary File

1 Datapresent in the form of characters Data is present in the encoded form

2 The plain text is present M the file. The image, audio or text data on be present M the
file.
3 It can not be corrupted easily. Even if single bits changed then the file gets
corrupted.
4 It can be opened and read using It can not read using the text editor like Notepad.
simple text editor like Notepad.

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

Opening Files
Opening a file
• In python there is a built in function open() to open a file.
Syntax
File_object=open(file_neme,mode)
Where File_object is used as a handle to the file.
Example
F=open("test.text")
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.
These are enlisted in the following table.
Different Modes in file:
In Python, there are several modes that can be used when opening a file:
1. 'r' (read mode) - This mode is used to read an existing file. The file must exist, otherwise a
FileNotFoundError is raised.
2. 'w' (write mode) - This mode is used to write to a file. If the file already exists, its contents are truncated
and overwritten. If the file does not exist, it is created.
3. 'a' (append mode) - This mode is used to append data to a file. If the file already exists, the new data is
added to the end of the file. If the file does not exist, it is created.
4. 'x' (exclusive creation mode) - This mode is used to create a new file, but only if it does not already exist. If
the file already exists, a FileExistsError is raised.
5. 'b' (binary mode) - This mode is used to read or write binary data, such as image or audio files. This mode
can be combined with the other modes by adding 'b' to the mode string, e.g. 'rb' for binary read mode.
By default, files are opened in text mode (i.e. 't'), which reads and writes text files. To open a file in binary
mode, you need to specify 'b' in the mode string.

Mode Purpose
‘r’ Open file for reading
‘w’ Open file for writing. If the file is not created, then create new file and then write.
If file is already existing then truncate it.
‘x’ Open a file for creation only. If the file already exists, the operation fails.
‘a’ Open the file for appending mode. Append mode is a mode in which the data is
inserted at the end of existing text. A new file is created if it does not exist.
‘t’ Opens the file in text mode

‘b’ Opens the file in binary mode


‘+’ Opens a file for updation i.e. reading and writing.

For example
fo = open("test.text”,w) # opens a file in write mode
fo = open("test.text”,rt) #Open a file for reading in text mode

Example : Write a python program to print the details of the file object

Solution:
fo = open("test.text”,r+)
print(fo)
Opening and Closing files:
In Python, you can use the built-in open() function to open a file and perform operations on it, and then
use the close() method to close the file. Here is an example:

# Open a file in write mode


file = open("example.txt", "w")

# Write to the file


file.write("Hello, world!")

# Close the file


file.close()

We can also use the with statement to open and automatically close a file, like this:

# Open a file in read mode using the "with" statement


with open("example.txt", "r") as file:
# Read the contents of the file
contents = file.read()

# The file is automatically closed after the "with" block.


In this example, we use the with statement to open a file named "example.txt" in read mode. We then
read the contents of the file using the read() method and store them in the contents variable. The file
is automatically closed when the with block is exited.

Reading and Writing files :

In Python, you can use the open() function to read and write files. The open() function returns a file
object that you can use to read or write to the file. Here is an example of how to read and write a file:

Writing to a File

To write to a file, you need to open the file in write mode ("w"). If the file does not exist, it will be
created. If the file already exists, its contents will be truncated (erased) before writing to it. You can
use the write() method to write to the file. Here's an example:

# Open a file in write mode


file = open("example.txt", "w")

# Write some text to the file


file.write("Hello, world!\n")
file.write("This is a new line.")
# Close the file
file.close()

Reading from a File

To read from a file, you need to open the file in read mode ("r"). You can use the read() method to
read the entire contents of the file, or the readline() method to read one line at a time. Here's an
example:

# Open a file in read mode


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

# Read the entire contents of the file


contents = file.read()
print(contents)

# Read one line at a time


file.seek(0) # Move the file pointer to the beginning of the file
line1 = file.readline()
line2 = file.readline()
print(line1)
print(line2)

# Close the file


file.close()

Directory and its methods:


A directory is a collection of files and subdirectories. A directory inside a directory is known as a
subdirectory. Python has the os module that provides us with many useful methods to work with directories
(and files as well). A directory (or folder) is a collection of files and other directories. We can perform
various operations on directories using Python's file handling functions.
Two popular Modules:
a) Os module
b) Shutil module
To work with directories in Python, you first need to import the os module, which provides a way to interact
with the operating system. The os module contains various functions for manipulating file paths, such as
creating, renaming, and deleting directories.

OS module: The os module in Python provides a range of functions for working with files and
directories at the operating system level. To use this module we need to import os module first.
import os
Some of the most commonly used functions in the os module for file handling include:
 os.mkdir(): Creates a new directory at the specified path.
import os
os.mkdir('mydir')
 os.makedirs(): Creates a new directory (and any necessary intermediate directories) at the specified
path.
 os.remove(): Deletes the file at the specified path.
 os.rmdir(): Deletes the directory at the specified path.
import os
os.rmdir('newdir')
 os.stat() : To get information about a file or directory, such as its size, creation time, or modification
time, you can use the os.stat() function.
 os.chdir(): Changing the current working directory.
import os
os.chdir('mydir')
 os.rename(): Renaming a directory.
import os
os.rename('mydir', 'newdir')
 os.walk(): Generates the file names in a directory tree by walking the tree either top-down or bottom-
up.
 os.path.join(): Joins two or more path components together to create a full path. This is useful for
constructing paths that are platform-independent.
 os.path.exists(): Checks whether a file or directory exists at the specified path.
import os
if os.path.exists('mydir'):
print('The directory exists')
else:
print('The directory does not exist')
 os.path.isfile(): Checks whether the specified path refers to a file.
 os.path.isdir(): Checks whether the specified path refers to a directory.

import os
path = 'mydir'
if os.path.isdir(path):
print(f"{path} is a directory")
else:
print(f"{path} is not a directory")

Shutil module:
shutil is a Python module that provides a higher-level interface for working with files and directories. The
name "shutil" is short for "shell utility", as it provides functions that mimic some of the functionality of shell
commands like cp (copy), mv (move), and rm (remove). To use this module we need to import first this
module.
Import shutil
The shutil module contains a variety of functions for copying, moving, renaming, and deleting files and
directories, as well as for archiving and compressing files. Some of the most commonly used functions in
the shutil module include:
 shutil.copy(): Copies a file from one location to another.
 shutil.copy2(): Copies a file from one location to another, preserving the metadata (e.g.
permissions, timestamps) of the original file.
 shutil.copytree(): Copies a directory (and all its contents) from one location to another.
 shutil.move(): Moves a file or directory from one location to another.
 shutil.rmtree(): Deletes a directory (and all its contents).
 shutil.make_archive(): Creates an archive (e.g. ZIP, TAR) of a directory.
 shutil.unpack_archive(): Extracts the contents of an archive into a directory.
The shutil module can be very useful for performing common file and directory operations in a simple and
efficient way.

Examples of File Handling:


[1] Create a text file “intro.txt” in python and ask the user to
write a single line of text by user input.
def program1():
f = open("intro.txt","w")
text=input("Enter the text:")
f.write(text)
f.close()
program1()

[2] Create a text file “MyFile.txt” in python and ask the user
to write separate 3 lines with three input statements from the
user.
def program2():
f = open("MyFile.txt","w")
line1=input("Enter the text:")
line2=input("Enter the text:")
line3=input("Enter the text:")
new_line="\n"
f.write(line1)
f.write(new_line)
f.write(line2)
f.write(new_line)
f.write(line3)
f.write(new_line)
f.close()
program2()
[3] Write a program to read the contents of both the files
created in the above programs and merge the contents into
“merge.txt”. Avoid using the close() function to close the
files.
def program3():
with open("MyFile.txt","r") as f1:
data=f1.read()
with open("intro.txt","r") as f2:
data1=f2.read()
with open("merge.txt","w") as f3:
f3.write(data)
f3.write(data1)
program3()
[4] Count the total number of upper case, lower case, and digits
used in the text file “merge.txt”.
def program4():
with open("merge.txt","r") as f1:
data=f1.read()
cnt_ucase =0
cnt_lcase=0
cnt_digits=0
for ch in data:
if ch.islower():
cnt_lcase+=1
if ch.isupper():
cnt_ucase+=1
if ch.isdigit():
cnt_digits+=1
print("Total Number of Upper Case letters are:",cnt_ucase)
print("Total Number of Lower Case letters are:",cnt_lcase)
print("Total Number of digits are:",cnt_digits)
program4()

[5] Write a program to count a total number of lines and count


the total number of lines starting with ‘A’, ‘B’, and ‘C’.
(Consider the merge.txt file)
def program5():
with open("merge.txt","r") as f1:
data=f1.readlines()
cnt_lines=0
cnt_A=0
cnt_B=0
cnt_C=0
for lines in data:
cnt_lines+=1
if lines[0]=='A':
cnt_A+=1
if lines[0]=='B':
cnt_B+=1
if lines[0]=='C':
cnt_C+=1
print("Total Number of lines are:",cnt_lines)
print("Total Number of lines strating with A are:",cnt_A)
print("Total Number of lines strating with B are:",cnt_B)
print("Total Number of lines strating with C are:",cnt_C)
program5()

[6] Find the total occurrences of a specific word from a text


file:
def program6():
cnt = 0
word_search = input("Enter the words to search:")
with open("merge.txt","r") as f1:
for data in f1:
words = data.split()
for word in words:
if (word == word_search):
cnt+=1
print(word_search, "found ", cnt, " times from the file")
program6()

[7] Read first n no. letters from a text file, read the first
line, read a specific line from a text file.
def program7():
cnt = 0
n = int(input("Enter no. characters to read:"))
with open("merge.txt","r") as f1:
line1=f1.readline()
print("The first line of file:",line1)
nchar=f1.read(n)
print("First n no. of characters:", nchar)
nline=f1.readlines()
print("Line n:",nline[n])
program7()

[8] Replace all spaces from text with – (dash).


def program8():
cnt = 0
n = int(input("Enter no. characters to read:"))
with open("merge.txt","r") as f1:
data = f1.read()
data=data.replace(' ','-')
with open("merge.txt","w") as f1:
f1.write(data)
program8()

[9] Write a program to know the cursor position and print the
text according to below-given specifications:
1. Print the initial position
2. Move the cursor to 4th position
3. Display next 5 characters
4. Move the cursor to the next 10 characters
5. Print the current cursor position
6. Print next 10 characters from the current cursor position
def program9():
f = open("merge.txt","r")
print(f.tell())
f.seek(4,0)
print(f.read(5))
f.seek(10,0)
print(f.tell())
print(f.seek(7,0))
print(f.read(10))
program9()

[10] Append the contents in entered by the user in the text


file:
def program10():
text = input("Enter text to append in the file:")
with open("merge.txt","a") as f1:
f1.write(text)
program10()

[11] Read the contents of file in reverse order:


def program11():
for i in reversed(list(open("merge.txt","r"))):
print(i.rstrip())
program11()

[12] Replace multiple spaces with single space in a text file.


def program12():
f1 = open("merge.txt","rt")
f2 = open("merge1.txt","wt")
for line in f1:
f2.write(' '.join(line.split()))
f1.close()
f2.close()
program12()
Method 2:
import re
def program12():
f1 = open("merge.txt","rt")
f2 = open("merge3.txt","wt")
for line in f1:
f2.write(re.sub('\s+',' ',line))
f1.close()
f2.close()
program12()

[13] Read a text file line by line and display each word
separated by a #.
f=open("MyFile.txt")
d=f.read()
s=''
for i in d:
s+=i.replace(' ','#')
print(s)
f.close()

[14] Read a text file and display the number of


vowels/consonants/uppercase/lowercase characters in the file.
f=open("MyFile.txt")
d=f.read()
v=0
c=0
u=0
l=0
for i in d:
if i.isupper():
u+=1
elif i.islower():
l+=1
if i.lower() in 'aeiou':
v+=1
elif i.isspace():
pass
elif i.lower() not in 'aeiou':
c+=1
print("Vowels:",v)
print("Consonants:",c)
print("Uppers:",u)
print("Lowers:",l)
f.close()
[15] Remove all the lines that contain the character ‘a’ in a
file and write it to another file.
f1=open("MyFile.txt")
f2=open("Temp.txt",'w')
l=f1.readlines()
for i in l:
if 'a' not in i:
f2.write(i)
f1.close()
f2.close()

[16]Program to counts the number of lines, tabs, and spaces in a


file.
filename = " MyFile.txt "

# Count the number of lines, tabs, and spaces in the file


num_lines = 0
num_tabs = 0
num_spaces = 0

with open(filename, "r") as file:


for line in file:
num_lines += 1
for char in line:
if char == "\t":
num_tabs += 1
elif char == " ":
num_spaces += 1

# Print the results


print(f"Number of lines: {num_lines}")
print(f"Number of tabs: {num_tabs}")
print(f"Number of spaces: {num_spaces}")

[17] Write a program in python to count number of vowels and


consonants present in the text file.
filename = " MyFile.txt "

# Count the number of vowels and consonants in the file


num_vowels = 0
num_consonants = 0

with open(filename, "r") as file:


for line in file:
for char in line:
if char.isalpha():
if char in "aeiouAEIOU":
num_vowels += 1
else:
num_consonants += 1

# Print the results


print(f"Number of vowels: {num_vowels}")
print(f"Number of consonants: {num_consonants}")

Dictionaries: A dictionary is an unordered collection of key-value pairs, where each key must be
unique. Dictionaries are mutable in Python. This means that you can modify the values associated
with a key, add new key-value pairs, or remove existing key-value pairs from a dictionary after it has
been created.

Here's how you can create, access, add, and update values in a dictionary:

Creating a dictionary:

You can create a dictionary using curly braces {} and separating each key-value pair with a colon :.
For example:

my_dict = {"apple": 2, "banana": 3, "orange": 1}

Accessing values in a dictionary:

You can access the value associated with a specific key in a dictionary using square brackets []. For
example:

print(my_dict["apple"]) # Output: 2

Updating a value in a dictionary:

my_dict["apple"] = 5

A dictionary is a collection of key-value pairs, where each key is unique and maps to a corresponding
value. Some of the most commonly used dictionary methods in Python include:

 dict.keys(): Returns a view object that contains the keys of the dictionary.
 dict.values(): Returns a view object that contains the values of the dictionary.
 dict.items(): Returns a view object that contains the key-value pairs of the dictionary as tuples.
 dict.get(key, default=None): Returns the value associated with the specified key, or the default
value if the key is not found.
 dict.pop(key, default=None): Removes the key-value pair with the specified key from the
dictionary, and returns the value associated with that key. If the key is not found, the default value
(if specified) is returned instead.
 dict.update(other_dict): Adds the key-value pairs from another dictionary to the current
dictionary. If a key from the other dictionary already exists in the current dictionary, the value for
that key is updated.
 dict.clear(): Removes all key-value pairs from the dictionary.
 dict.copy(): Returns a shallow copy of the dictionary.

# Create a dictionary of programming languages


languages = {
'Python': 'Guido van Rossum',
'Java': 'James Gosling',
'C++': 'Bjarne Stroustrup',
'JavaScript': 'Brendan Eich'
}

# Print the keys of the dictionary


print(languages.keys())

# Print the values of the dictionary


print(languages.values())

# Print the key-value pairs of the dictionary


print(languages.items())

# Get the value associated with the key 'Python'


print(languages.get('Python'))

# Remove the key-value pair with the key 'C++'


languages.pop('C++')

# Add a new key-value pair to the dictionary


languages['Ruby'] = 'Yukihiro Matsumoto'

# Update the values for the keys 'Java' and 'JavaScript'


languages.update({
'Java': 'James Gosling and Sun Microsystems',
'JavaScript': 'Netscape Communications Corporation'
})

# Print the updated dictionary


print(languages)

**********************End******************************

You might also like