PPS - NOTES - Unit-6 .
PPS - NOTES - Unit-6 .
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.
• 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.
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.
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.
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
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:
We can also use the with statement to open and automatically close a file, like this:
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:
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:
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.
[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()
[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()
[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()
[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()
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:
You can access the value associated with a specific key in a dictionary using square brackets []. For
example:
print(my_dict["apple"]) # Output: 2
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.
**********************End******************************