Python file handling

By

  • Files are basically used to store and write the data.
  • Files are used to permanently store the data in a non volatile memory(pen drive ,hardisk).
  • We were taking the input from the console and writhing it back to the console.It is not enough,if we want to display more data then it is not display on the console because data are temporely stored in RAM (volatile memory).when we off or shut down the computer/pc ,data will be lost.So that here file input/output concepts are more important.
  • The file handling plays an important role when the data needs to be stored permanently into the file.
  • When we use files,we can access the stored information after the program termination because files are non volatile storage.
  • When we want to read ,write and modify the file ,we  need to open it first.
  • After performing the read ,write and modification in the file,we have to close the file.
Hence a file operation can be done in the following order.
  1. Open a file.
  2. Read or write(operations)
  3. Close the file.
Opening a file:-
  • Python has a built-in  open() function to open a file.
  • An open() function accepts two arguments, File_name and Access mode in which is accessed .
  • This function returns a file object.When can be used to perform various operations like reading ,writhing,modifing the file accordingly.
Syntax:-
file object = open (<file_name>,<access mode>,buffering)
  • The files can be accessed using various mode like Read,Write or append .We want to open the file in text mode or binary mode.
  • The default is reading in text mode.we get strings when reading from the file in this mode.
  • The binary mode returns bytes.It is used when dealing with  non-text files likes .exe file or images. 
There are some details about the access mode to open a file.
1.) r --> It opens the file to read-only mode. The files are by default open in this mode if  no access mode is specified.The file pointer exists at the begining.
2.) r+ --> It opens the file to read and write both.The file pointer exists at the begining of the file.
3.) rb --> It opens the file to read-only in binary format.The file pointer exists at the begining of the file.
4.) rb+ --> It opens the file to read and write both in binary format .The file pointer exists at the begining of the file.
5.) w --> It opens the file to write mode only.It creats a new file if no file exists with the same name other wise  overwrites the file if exists.The file pointer exists at the begining of the file.
6.) w+ --> It opens the file to read and write both.It overwrites the previous file if exists other wise it creates new file if no file exists. But in r+ if file is exists,it does not overwrite the previous written file.The file pointer exists at the begining of the file.
7.)  wb --> It opens the file to write only in binary format.It creates new file if no  file is exists otherwise overwrites the file if it exists.The file pointer exists at the begining of the file.
8.) wb+ --> It opens the file to write and read both in binary format.The file pointer exists at the beging of the file.
9.)  a --> It opens the file in append mode.The file pointer exists at the end of the previous written file if no file exists with the same name.
10.) a+ --> It opens a file  in append and read both.It creates a new file if no file exists with the same name.If the file is exists with same name then file pointer exists at the end of the previous written files.
11.) ab --> It opens the file in the appened mode in biinary format.The file pointer exists at the end of the previous written file.Otherwise it creates new file in binary format if no file exists with the same name.
12.) ab+ --> it opens a file to append and read both in binary format.The file pointer exists at the end of the file.
e.g. 
 # open the file.txt in read mode
file_ptr=open("file.txt","r")
if file_ptr:
    print("This file is opened successfully")
Output:-
This file opened successfully
>>> 
Description:-
  • First we have created a file as a name file.txt .
  • Here We have passed file_name file.txt as a first argument and opened file in read mode 'r' as mentioned in second argument.
  • The file_ptr holds the file object,if the file is opened successfully then it will executed the print statement.
Closing the files in python 
  • When we are done with performing operations on the files,we have to properly close the file.
  • We can perform any operation on the file using the system. which is currently opened in python.We have to practice to close the file if all perations are done.
Syntax:-
file_object.close()
e.g.
# open the file.txt in read mode
file_ptr=open("file.txt","r")
if file_ptr:
    print("This file is opened successfully")
#Now close the opened file
file_ptr.close()  
Output:-
This file is opened successfully
>>> 
Note:-
  • After closing the file,we can not perform any operation in the file.
  • This method is not entirely safe.If an exception occcurs when we are performing some operation with the file,the code exists without closing the file.
e.g.
try:
    file_ptr=open("file.txt","r")
    print("This file is opened successfully")
finally:
    file_ptr.close()
Output:-
This file is opened successfully
>>> 
The 'with' statement:-
  • The with statement was introduced in python 2.5.
  • This with statement is more important in the case of manipulating the files.
  • This with statement is used where a pair of statements to be executed.
syntax:-

with open (<file_name>,<access.mode>) as <file_pointer>:
#statement suite
Note:-
  • The advantage of using this with statement is that, it provides the guarantee to close the file regardless of how many the nested block exists.
  • We have to use the 'with' statement,if the break,reurn or exception occurs in the nested block of code the it automatically close the file.we don't need to write the close() method.
e.g.
with open("file.txt",'r')as f:
    data=f.read()
    print(data)
Output:-
Hi friends, how are you?
>>>
Writing the file in python:-
  • To write a file in python,we need to open it in write w , append a or exclusive creation x mode.
  • we have to be careful with w mode because ot will overwrite the file if it already exists .due to this all the previous data are destroyed.
  • w: It will overwrite the file if any file exists.
  • a: It will append the existing file.The file pointer is at the end of the file.It creates a new file if no such file exists.
e.g.1
#create a file if no such file exists
file_ptr=open("file.txt",'w')
#write string or sequence of bytes
file_ptr.write("Welcome to MNT LAB.This provides simple and point to point tutorials.")
#closing the opened file
file_ptr.close()
#open the content of this file
f=open("file.txt",'r')
value1=f.read()
print(value1)    
Output:-
Welcome to MNT LAB.This provides simple and point to point tutorials.
>>> 
Descriptions:-
  • Here we have opened the file in 'w' mode.The file name (file.txt) does not exists.So it created new file as file.txt on desktop(your file location) .We have written the content in the file using write() function.
  • After that we have open the file in read mode and print the file.txt data.
e.g.2
#open the existing file.txt in append mode
f=open("file.txt",'a')
#write the contents or string at the existing contents of the file.txt file.
f.write("This website provides the python tutorials.")
#closing the opened file
f.close()
#open the content of this file
f=open("file.txt",'r')
value1=f.read()
print(value1) 
Output:-
Welcome to MNT LAB.This provides simple and point to point tutorials.This website provides the python tutorials.This website provides the python tutorials.This website provides the python tutorials.
>>> 
Descriptions:-
  • Here we have opened the file in 'a' mode and append some contents in existing file.txt file.
Reading files in Python:-
  • To read a file in python,we have to open the file in read 'r' mode.
  • The read() method reads a string from the file.It can read the data in the text  as well as  a binary format also.
Syntax:-

file_ptr.read(<count>)
Note:-
  • Here 'count' is the number of the bytes to be read from the given file(file.txt).
  • If no 'count' is specified,it will read the content of the file(file.txt) until the end.
e.g.1
#open the file.txt file,if no such file is exists.It will show error.
f=open("file.txt",'r')
#Now read the file.txt first 10 bytes and store in a variable(value1)
value1=f.read(70)
#print the data stored in value1
print(type(value1))
print(value1)
#closing opened file
f.close()
Output:-
<class 'str'>
Welcome to MNT LAB.This provides simple and point to point tutorials.T
>>> 
e.g. 2
#open the file.txt file,if no such file is exists.It will show error.
f=open("file.txt",'r')
#Now read the file.txt complete and store in a variable(value1)
value1=f.read()
#print the data stored in value1
print(type(value1))
print(value1)
#closing opened file
f.close() 
Output:-
<class 'str'>
Welcome to MNT LAB.This provides simple and point to point tutorials.This website provides the python tutorials.This website provides the python tutorials.This website provides the python tutorials.
>>> 
e.g 3
#open the file.txt file,if no such file is exists.It will show error.
f=open("file.txt",'r')
a=f.read(20) #read the first 40 characters
print(a)
b=f.read(30) #read the next 30 characters
print(b)
c=f.read() #read the next till end of the file.
print(c)
d=f.read() #now reading it returns empty string
print(d)
e=f.tell() #get the current file position 
print(e)
g=f.seek(5)#change the file cursor(pointer)to 5th position.
print(g)
h=f.read()# read the file from 5th position to the end of the file
print(h)
Output:-
Welcome to MNT LAB.T
his provides simple and point 
to point tutorials.This website provides the python tutorials.This website provides the python tutorials.This website provides the python tutorials.

198
5
me to MNT LAB.This provides simple and point to point tutorials.This website provides the python tutorials.This website provides the python tutorials.This website provides the python tutorials.
>>> 
  • In python ,we can easily read file line by line by using a readline() method.
  • This readline method reads the lines of the file from the begining.
  • If we want to reads first three lines of the file,we need to write readline() method three times.
e.g.
f=open("file.txt",'r')
#store all the data of the files in variable 'value1' and 'value2'
value1=f.readline()
value2=f.readline()
print(value1)
print(value2)
f.close()
Output:-
Welcome to MNT LAB.This provides simple and point to point tutorials.

This website provides the python tutorials..

>>> 
Note:-
  • Here we have called the redline() method two times that's why it read two lines from the file.
  • The readline() method returns a list of remaining lines of the entire file.
  • All these reading methods returns empty values when the end of file(EOF) is reached
We can also read a file a file line by line using a for loop
e.g. 

f=open("file.txt",'r')
for line in f:
    print(line,end='')
f.close()
Output:-
Welcome to MNT LAB.This provides simple and point to point tutorials.
This website provides the python tutorials..
This website provides the.NET tutorials.
>>> 
Note:-
It is an alternate way to read the file content line by line as wel read in readline() method.
Creating a new file in Python
  • The new file can be created by using the access modes with the function open()
  • x: It create a new file with the specified name.It causes an error if file exists with the same name.
  • w:It create a new file with the specified name if no such file exists.
  • 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 exists with the specified name.
e.g.
#open the file.txt in read mode
f=open("file5.txt",'x')
print(f)
if f:
    print("file create successfully")
f.close()
Output:-
<_io.TextIOWrapper name='file6.txt' mode='x' encoding='cp1252'>
file create successfully
>>>
Get file pointer positions:-
Python provides the tell() method to get the curssor or file location or file pointer of the file at which the file pointer currently exists.
Syntax:-

file_ptr.tell()
e.g.
#open the file.txt in read mode
f=open("file.txt",'r')
print("The file pointer at the point:",f.tell())
#Now read the content of the file
data=f.read()
#After read get the content file pointer
print("After reading the file cursor or pointer at the point:",f.tell())
Output:-
The file pointer at the point: 0
After reading the file cursor or pointer at the point: 157
>>> 
Modifying file pointer position

  • Sometimes we have to change the file pointer location externaly scince we can have to read or write the content of various locations.
  • For this purpose,python provides the seek() method,which enables us to modify thef ile pointer position/cursor position externaly.
Syntax:- 
file_ptr.seek(offset,from)
The seek() method accepts two parameters.
1.) offset: It refers to the new position of the file pointer within the file.
From
2.) from:
  • It indicates the reference positions from where the bytes are to be moved.
  • If we set it to zero(0),the begining of the file is used as the reference position.
  • If we set it to 1,the current position of the file pointer is used as the reference position.
  • If we set it to 2,the end of the file position is used as the reference position.
e.g.
#open the file.txt in read mode
f=open("file.txt",'r')
#initially the file pointer is at Zero(0)
print("The file pointer position is:",f.tell())
#now change the file pointer location at 8
f.seek(10)
#Now get current position of the file pointer
print("After this file pointer position is:",f.tell())
Output:-
The file pointer position is: 0
After this file pointer position is: 10
>>>
Some other pythoon file methods:-
  • File.flush():It flushes the internal buffer.
  • File.next():-It returns the next line from the file.
  • File.truncate(size):-It truncates the file to the optional specified size.
  • File.writelines(seq):-It writes a sequence of the string to a file.
For More...

0 comments:

Post a Comment

Powered by Blogger.