Unit 6
Unit 6
• r(read):-
Read mode is used when the file is only being read. Places the file
pointer at the beginning of file.
• w(write):-
Write mode which is used to edit and write new information to file.
Truncates and overwrites the file, if the file exists and creates new file,
if the file does not exist.
• a(append):-
Appending mode, which is used to add new data to the end of the file.
New information is automatically adjusted to the end.
• Opening file in different modes
• r : Opens a file for reading only. The file pointer is placed at the beginning of
the file. This is the default mode.
• w : Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
• a : Opens a file for appending. 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.
• r+ : Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
• w+ : Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and writing.
• a+ : Opens a file for both appending and reading. 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.
• Opening file in different modes
• 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.
• buffering:-If the buffering value is set to 0,no buffering takes palce.If the
buffering value is 1,line buffering is performed while accessing file.
• If we specify the buffering value as an integer greater than 1,then buffering
action is performed with the indicated buffer size. If negative, the buffer
size is the system default(default behavior).
Built-in function and attributes:-
• read():-To read and return complete contents of file.
• mode:-This attribute contains mode of file in which it is opened.
• name:-This attribute contains name of file.
• closed:-Contains whether file is closed or not.
• close():-Close file and releases file pointer from it.
Ex:-
f=open(“sample.txt”,”r”)
print(“file is opened”)
print(“contents of file:\n”,f.read())
f.close()
print(“file is closed.”,f.closed)
print(“File name is:”,f.name)
print(“File opened in”,f.mode,”mode”)
Reading and writing file
• The write method writes any string into a file.
• Syntax:-
file_obj.write(string_data)
Write() method does not add a newline character(“\n”) to end of the string.
• Ex:-
f=open(“sample.txt”,”w”)
f.write(“This is a file-1.\n”)
f.write(“This is a file-2.\n”)
f.close()
print(“data saved”)
• Writelines():- This function writes a sequence of string to the file.
Ex:- f=open(“sample.txt”,”w”)
list1=[“this is line-1”,”this is line-2”,”this is line-3”,”this is line-4”]
f.writelines(list1)
f.close()
Reading and writing file
• The read() function reads from opened file and returns as string.
Read() function has a parameter, which is length/characters to read.
• readline():- this function reads only one line, in which currently file
pointer is pointing.
• Ex:-
f=open(“simple.txt”,”r”)
print(f.read())
position = f.tell()
print ("Current file position : ", position)
f.seek(0)
print(f.read(12))
f.seek(0)
print(f.readline())
f.close()
#it will read content of file upto-end of file
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1 = open("myfile.txt","r+")
file1.seek(0)
file1.seek(0)
# readlines function
print ("Output of Readlines function is ")
print(file1.readlines())
file1.close()
Closing a file
• To close a file, we have built-in close function. This function doesn’t have
parameter.
• Ex:-
f=open(“sample.txt”,”r”)
f.close()
Renaming a file
• To rename a file in python, the os module needs to be imported. The
rename() method is used to rename the file.
• Syntax:- os.rename(current_file_name,new_file_name)
• Ex:-
import os
print(“content of pwd”,os.listdir())
os.rename(“sample.txt”,”sample1.txt”)
print(“content of pwd”,os.listdir())
Deleting a file
• The remove() in python programming is used to remove existing file with
file name.
• This method is used to delete files by supplying the name of the file to be
deleted as a argument.
• Syntax:- os.remove(file_name)
• Ex:-
import os
print(“content of pwd”,os.listdir())
os.remove(“sample.txt”)
print(“content of pwd”,os.listdir())
Directories in python
• A directory is a collection of files and sub directories. Python has the os
module, many built-in functions to work with directories.
Syntax:-os.getcwd()
Ex:- import os
print(os.getcwd())
o/p:-C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\
Python Practice’
Directories in python
• List Directories and files:-
All files and sub-directories inside a directory can be known using
listdir() method.This method takes in a path and returns a list of sub
directories and files in that path. If no path is specified, it returns from the
current working directory.
• Ex:-
import os
print(os.listdir())
• Changing Directory:-
We can change the current working directory using the chdir() method.
The new path that we want to change must be supplied as a string to this
method. Use the both forward(/) and backward(\) to separate path
elements.
Syntax:-os.chdir(“dirname”)
Ex:- import os
print(os.getcwd()) # O/P: ‘d:\\IT’
os.chdir(“d:\IT\SYCO”)
Directories in python
• Create new directory:-
We can make a new directory using the mkdir() method.
This method takes in the path of the new directory.If the full path is not
specified, the new directory is created in the current working directory.
• Syntax:- os.mkdir(“new directory”)
Ex:- import os
os.mkdir(“dir1”)
• Rename a directories:-
To rename a file or directory of file we have rename()function.
Syntax:- os.rename(“current directory/file”,”new directory/file”)
• Ex:- import os
print(“Initial it has”)
print(os.listdir())
os.rename(“MyOld”,”MyNew”)
print(“after rename it has”)
print(os.listdir())
Directories in python
• Removing a directory:-
The remove() function is to delete file or directory,by specifing its name as
the argument.
Syntax:- os.remove(file_name)
Ex:- import os
print(os.listdir())
os.remove(“dir2”)
print(“after removing”)
print(os.listdir())
Exception Handling
• When we execute a python program ,there may be uncertain
conditions may occur, known as errors.
• An exception is an event which occurs during execution of the
program that disrupts the normal flow of the execution of the
program.
• In python programming we can handle exception using try-except
statement, try-finally statement and raise statement.
• Ex:-
1)print(“15/0 is”,15/0)
o/p:-ZeroDivisionError:division by zero
2)a=[10,20,30]
print(“Second element:”,a[1])
print(“forth element:”,a[3])
o/p:- Index Error:-list index out of range
Exception Handling