0% found this document useful (0 votes)
55 views32 pages

Unit V

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

Unit V

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

UNIT – IV

Topics to be covered:
 Introduction to Files,
 File Handling,
 Working with File Structure,
 Directories,
 Handling Directories
 Sometimes, it is not enough to only display the data on the
console.
 The data to be displayed may be very large, and only a limited
amount of data can be displayed on the console, and since the
memory is volatile, it is impossible to recover the
programmatically generated data again and again.
 However, if we need to do so, we may store it onto the local file
system which is non volatile and can be accessed every time.
 Here, comes the need of file handling.
 Python provides the facility of working on Files.
 File is a named location on disk to store related information. It is
used to permanently store data in a non-volatile memory(e. g. hard
disk)
 Since, random access memory(RAM) is volatile which loses its
data when computer is turned off, we use files for future use of the
data.
 A File is an external storage on hard disk from where data
can be stored and retrieved.
 A file is a chunk of logically related data or information
which can be used by computer programs.
Types of Files:
There are 2 types of files
Text File: text files stores the data in the form of characters
eg: abc.txt
Binary File: binary files stores data in the form of bytes
eg: images, video files, audio files etc...
 When we want to read from or write to a file we need to open
it first. When we are done, it needs to be closed, so that
resources that are tied with the file are freed
 A file operation takes place in the following order:
1.Open a file
2.Read or write (perform operation)
3.Close the file
Opening a File:
Python provides the open() function which accepts two
arguments, file name and access mode in which the file is
accessed.
The function returns a file object which can be used to
perform various operations like reading, writing, etc.
Syntax:
fileObject=open(file_name,access_mode,buffering)
here,
file_name: It is the name of the file which you want to access.
access_mode: It specifies the mode in which File is to be opened.
 There are many types of mode like read, write, append.
 Mode depends the operation to be performed on File.
 Default access mode is read.
buffering:
 If the buffering value is set to 0, no buffering takes place.
 If the buffering value is 1, line buffering is performed while
accessing a file
Example
f = open("python.txt",'w') # open file in current directory
f = open("/home/rgukt/Desktop/python/hello.txt")
# specifying full path
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
2. Relative path

1.Absolute path:
Which always begins with the root folder
2. Relative path:
Which is relative to the program’s current working directory..
The absolute path includes the complete directory list required to locate the file.
Modes of file:
rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
wb
Opens a file for writing only in binary format. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
ab
Opens a file for appending in binary format. The file pointer is at the end of the file
if the file exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.
rb+
Opens a file for both reading and writing in binary format. The file pointer placed at
the beginning of the file.
wb+
Opens a file for both writing and reading in binary format. Overwrites the existing
file if the file exists. If the file does not exist, creates a new file for reading and
writing.
ab+
Opens a file for both appending and reading in binary format. The file pointer is at
the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.
Closing Files in Python
When we are done with performing operations on the file, we need to
properly close the file.
Python has a garbage collector to clean up unreferenced objects but we
must not rely on it to close the file.
Closing a file will free up the resources that were tied with the file. It
is done using the close() method available in Python.
Syntax: file object. close( )
f = open("test.txt")
f.close()
Here, the file represented by the file object f is closed. It means f is
deleted from the memory. Once the file object is lost, the file data will
become inaccessible. If we want to do any work with file again,we
should once again open the the file using the open() function
Writing data to text files:
We can write character data to the text files by using
thefollowing 2 methods.
write(str)
writelines(list of lines)
Creating a new file
• The new file can be created by using one of the
following access modes with the function open().
• x: it creates a new file with the specified name. It
causes an error a file exists with the same name.
• a: It creates a new file with the specified name if
no such file exists. It appends the content to the
file if the file already exists with the specified
name.
• w: It creates a new file with the specified name if
no such file exists. It overwrites the existing file.
The with statement:
 The with statement can be used while opening a file.
 We can use this to group file operation statements within a block.
 The advantage of with statement is it will take care closing of file,
after completing all operations automatically even in the case of
exceptions also, and we are not required to close explicitly.
program to append text and display the contents of file on the screen
f1= open(“myfile.txt”,”a+)
f1.append(“God is great”)
f1.seek(0,0)
print(f1.read())
f1.close()
Output: Hi how r u
I am fine
God is great
program to replace a word with other word in a file
f1=open(“myfile.txt”,”r+”)
str=f1.read()
str.replace(“fine”,”good”)
f1.write(str)
f1.close()

Output:Hi how r u
I am good
#Program to read text from a file using for loop
f1=open(“myfile.txt”,”r”)
for line in f1:
print(line)
f1.close()
Output:
Hi how r u
I am fine

Program to copy the contents of one file to other file


f1=open(“myfile.txt”,”r”)
f2=open(“mydata.txt”,”w”)
s=f1.read()
f2.write(s)
print(“File copied,open the file and see”)
f1.close()
f2.close()
Program to count number of characters,words and lines in a text file.
cl=cw=cc=0
f1=open(“myfile.txt”,”r”)
for line in f1:
cl+=1
words=line.split()
cw+=len(words)
cc+=len(line)
print(“Number of lines=“,cl)
print(“Number of words=“,cw)
print(“Number of characters=“,cc)
f1.close()

Output:
Number of lines=2
Number of words=7
Number of characters=19
Working with binary files
File Pointer positions
tell():
 We can use tell() method to return current position of the
cursor(file pointer) from
 beginning of the file. [ can you please tell current cursor
position]
 The position(index) of first character in files is zero just like
string index.
seek():
 We can use seek() method to move cursor(file pointer) to specified
location. [Can you please seek the cursor to a particular location]
f.seek(offset, fromwhere)
Here, offset represents the number of positions to move, from where
represents from which position to move and from where can be 0,1 or 2
0---->From beginning of file(default value),1---->From current
position,2--->From end of the file
Note: Python 2 supports all 3 values but Python 3 supports only zero.
f=open("sample.txt","r")
f = open(“sample.txt", "w") f.seek(1)
f.write("abcdefghijklmnop") print(f.read(5))
f.close() f.seek(2)
print(f.read(1))
f.close()

Output:
bcdef
c
Python os module
• The os module provides us the functions that are
involved in file processing operations like renaming,
deleting, etc.
How to check a particular file exists or not?
• We can use os library to get information about files in
our computer.
• os module has path sub module, which contains isFile()
function to check whether a particular file exists or not?
• os.path.isfile(fname)
Note:
• sys.exit(0) To exit system without executing rest of the
program.
• argument represents status code .
• 0 means normal termination and it is the default value.
Renaming the file
 The os module provides us the rename() method which is
used to rename the specified file to a new name.
 The syntax to use the rename() method :
rename(“current-name”, ”new-name”)
Ex: import os;
os.rename("abc.txt",“snist.txt")
Removing the file
 The os module provides us the remove() method which is
used to remove the specified file.
 The syntax to use the remove() method:
remove(“file-name”)
Ex: import os;
os.remove(“snist.txt")
What is Directory in Python?
• If there are a large number of files to handle in your Python
program, you can arrange your code within different directories to
make things more manageable.
• A directory or folder is a collection of files and sub directories.
• Python has the os module, which provides us with many useful
methods to work with directories (and files as well).
Working with Directories:
• It is very common requirement to perform operations for
directories like
1. To know current working directory
2. To create a new directory
3. To remove an existing directory
4. To rename a directory
5. To list contents of the directory etc...
Directories
A directory is a folder which holds other directories and sub
directories.To work with directories,we have methods from os
module.
Methods:
1.getcwd():It is used to get the path of current working directory.
Ex: import os
print(os.getcwd())
Output: C;\Users\Student\Desktop
2.mkdir():The mkdir() method is used to create the directories in
the current working directory.
syntax to create the new directory :mkdir(“directory name”)
Ex: import os;
#creating a new directory with the name new
os.mkdir("new")
#creating sub directory sub
os.mkdir(‘new\sub’)
3.makedirs():It is used to create directory and a subdirectory in
curtrent working directory.
Ex: import os
os.makedirs(“new/sub1/sub2”)
4.chdir():The chdir() method is used to change the current working
directory to a specified directory.
syntax to use the chdir() method: chdir("new-directory")
Ex: import os;

#changing the current working directory to new


os.chdir("new")
5.rmdir():The rmdir() method is used to delete the specified directory.
syntax to use the rmdir() method: os.rmdir(“directory name”)
import os;
#removing the new directory
os.rmdir("new")
6.removedirs():It is used to remove all the directories given as
argument.
Ex: import os
os.removedirs(“new/sub1/sub2")
8.rename():It is used to rename a directory.
Ex: import os
os.rename(“old”,”new”)
8.listdir():It is used to show the directories and files residing in
current working directory.
Ex: import os
print(os.listdir())

You might also like