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

UNIT-VI File Handling and Exception Handling

This document covers file input/output handling and exception handling in Python, detailing how to create, read, write, and delete files, as well as manage directories. It explains different file modes, methods for accessing file contents, and the use of the os module for file and directory operations. Key functions such as open(), read(), write(), rename(), and remove() are highlighted along with examples for clarity.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

UNIT-VI File Handling and Exception Handling

This document covers file input/output handling and exception handling in Python, detailing how to create, read, write, and delete files, as well as manage directories. It explains different file modes, methods for accessing file contents, and the use of the os module for file and directory operations. Key functions such as open(), read(), write(), rename(), and remove() are highlighted along with examples for clarity.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

================================================

UNIT-6 File I/O Handling and Exception Handling


================================================
***Files***
===========
- File is a collection of related records.
- File is used to store the records permanently.
- File is used to store and access records.
- File is computer resource user for recording data in computer storage device.
- Processing on file is performed using read/write operations.
- Python supports file handling and allows user to handle file.
- We can perform many operations on file like creating file, updating file,
deleting file, etc.
- There are two different types of file
1) Text Files:
- Text files are simple text in human readable format. It is collection of sequence
of text.

2) Binary Files:
- Binary files have binary data i.e 0s and 1s which is understood by the computer.

- We follow below orders while working with file:


I) Open a File.
II) Read or Write Files.
III) Close the file.

Opening file in different Modes:


--------------------------------
- All files in python are required to be open before some operation.
- While opening file, file object got created and by using that file object we will
perform different operations.
- Python has built-in function open() to open a file.
- Syntax:
fileObject=open(FileName[,AccessMode,buffering]);
- Where:
FileName : Name of the file wthat you want to access.
AccessMode: The access mode determines the mode in which the file has to be
opened i.e read,write, append, etc.
buffering: If the buffering value set to 0 then no buffering takes place. If
the buffering value is 1 then buffering is performed while accessing file.
- Example:
file=open("vjtech.txt");

Different Modes of Opening File:


---------------------------------
1) r : Opens file for reading mode.
2) r+ : Opens file for both reading and writing.
3) w : Opens file for writing only.
4) w+ : Opens file for both reading and writing.
5) a : Opens file for appending.
6) a+ : Opens file for both appending and reading.
7) rb : Opens file for reading only in binary format.
8) rb+: Opens file for both reading and writing in binary format.
9) wb : Opens file for writing only in binary format.
10)wb+: Opens file for both reading and writing in binary format.
11)ab : Opens file for appending in binary format.
12)ab+: Opens file for both appending and reading in binary format.

- Example:
file=open("vjtech.txt",'w');
- In above example vjtech.txt file opens in writing mode.

Accessing contents of file using standard library functions:


-----------------------------------------------------------
1) file.closed : return true if file is closed.
2) file.mode : return access mode of file.
3) file.name : return name of the file.
4) file.encoding: return encoding of the file.

Closing File:
--------------
- When we are done with all operations to the file then we need to properly close
the file.
- Closing the file will free up the resources that allocated by the file.
- Syntax:
fileobject.close();

==========================
Writing Data to a File:
==========================
- We use write() function to write string in file.
- If we want to write some contents into a file then we have to open the file in
"w" or "a" mode.
- The write() method writes the contents onto the file. It takes only one parameter
and returns the number of characters writing to the file.
- If we open the file in "w" mode then contents of the file got override.
- And if we open the file in "a" mode then new contents added at last.
- There are two different write() methods available for write the data.
1)write(string):
-----------------
- This method write contents of string to the file and return no of characters
written.
- Example:
#write data into a file using write() method
f1=open("vjtech.txt","w");
f1.write("This is Python Language\n");
f1.write("This is Object Oriented Programming Language\n");
f1.write("We are learning this language in VJTech Academy");
print("Data written successfully in file!!!");
f1.close();

2) writelines(list):
---------------------
- It writes sequence of strings to the file and there is no any return value.
- Example:
#write data into file using writelines() method.
f1=open("sample.txt","w");
msg=["VJTech Academy\n","MSBTE\n","Maharashtra\n","Pune\n"];
f1.writelines(msg);
print("Data written successfully into the file!!!");
f1.close();

==========================
Reading Data from File:
==========================
- To read a file in python, we must open the file in reading mode("r" or"r+").
- The read() method in python reads contents of the file.
- This method returns the characters read from the file.
- There are three different read() methods available for read the data.
1) read([n]):
--------------
- This method read the complete contents of the file if you have not specified n
value.
- But if you given the value of n then that much of characters read from the file.
For example, suppose we have given read(3) then we will get back the first three
characters of the file.
- Example:
#read contents of the file using read() method
f1=open("vjtech.txt","r");
print(f1.read(5)); #read first 5 data
print(f1.read(10)); #read next 10 data
print(f1.read()); #read rest of the file data

2) readline([n]):
-----------------
- This method just output the entire line.
- But if we spcify the value of n then it will return n bytes of single line of the
file.
- This method does not read more than one line.
- Example:
#read contents of the file using readline() method
f1=open("sample.txt","r");
print(f1.readline()); #read first line
print(f1.readline(3)); #read first three character of line
print(f1.readline(4)); #read next 4 characters of the line

3) readlines():
----------------
- This method is used to read complete lines of the file.
- Example:
#read contents of the file using readlines() method
f1=open("sample.txt","r");
print(f1.readlines()); #read complete lines of the file

-Output:
['VJTech Academy\n', 'MSBTE\n', 'Maharashtra\n', 'Pune\n']

==============
File Position
==============
- We can change the position of file cursor using seek() method.
- tell() will return the current position of file cursor.
- Syntax:
f.seek(offset,reference_point);
- The position is computed from adding offset to a reference point.
- Reference point can be ommited and default to 0.
- Following values we can use for reference point.
I) 0 : beginning of the file
II) 1 :current position of the file
III) 2: end of the file.
- tell() method is used to find the current position of the file pointer in the
file.
- seek() method is used to move file pointer to the particular position.
- Example:
#file position
f1=open("vjtech.txt","r");
print("current position of file cursor:",f1.tell());
print(f1.read());
print("current position of file cursor:",f1.tell());
f1.seek(0);
print(f1.read());

=================
Renaming the file
=================
- Renaming the file in python is done with the help of rename() method.
- To rename a file in python, the os module needs to be imported.
- rename() method takes two arguments current file nane and new file name.
- Syntax:
os.rename(current_file_name,new_file_name);
- Example:
#for renaming the file
import os;
print("***Contents of present working directory****");
print(os.listdir());
os.rename("sample.txt","sample123.txt");
print("***Contents of present working directory after rename****");
print(os.listdir());

=================
Deleting a file
=================
- We can use remove() method to delete files.
- TO remove file, os module need to be imported.
- This method used in python to remove the existing file with the file name.
- Syntax:
os.remove(file_name);
- Example:
#for deleting files
import os;
print("***Contents of present working directory****");
print(os.listdir());
os.remove("sample123.txt");
print("***Contents of present working directory after remove****");
print(os.listdir());

==============
Directories
==============
- If there are a large number of files to handle in the python program, we can
arrange the code within different directories to make things more manageable.
- A directory or folder is a colletion of files and sub-directories.
- Python has the os module which provides us with many useful methods to wortk with
directories.

1) Create new directory:


---------------------------
- We can make new directory using mkdir() method.
- This method takes in the path of the new directory. If the full path is not
specified then new directory is crated in the current working directory.
- Syntax:
os.mkdir("newdir");
- Example:
#create new directory
import os;
os.mkdir("testdir123");
print("new directory created successfully!!!");

2) Get Current Directory:


--------------------------
- We can get the present working directory using getcwd() method.
- This method return the current working directory in the form of string.
- Syntax:
os.getcwd();
- Example:
#Get current directory
import os;
print(os.getcwd());

3) Changing the directory:


---------------------------
- We can change the current working directory using chdir() method.
- We can pass new path of directory in this method.
- We can use both forward slash(/) and backward slash(\) to separate path elements.
- Syntax:
os.chdir("dirname");
- Example:
#changing directory
import os;
print(os.getcwd());
os.chdir("F:\Academic 2022\C Language 2022");
print(os.getcwd());

4) List directories and files:


-------------------------------
- All files and sub directories inside a directory can be display using listdir()
method.
- This method takes in a path and return a list of sub directories and files in
that path.
- If path is not specified then it will return from the current working directory.
- Exmaple:
#display lis of files and directories.
import os;
print(os.listdir());

5) Removing directory:
-----------------------
- The rmdir() method is used to remove directories in the current directory.
- Syntax:
os.rmdir("dirname");
- Example:
#display lis of files and directories.
import os;
print("***List of files and directories****");
print(os.listdir());
os.rmdir("testdir123");
print("***List of files and directories after remove****");
print(os.listdir());

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy