Learn Python – Python File Handling- Basic and advance

Till now, we had been taking the enter from the console and writing it returned to the console to interact with the user.

Sometimes, it is no longer adequate to solely show the facts on the console. The statistics to be displayed may additionally be very large, and only a limited quantity of information can be displayed on the console due to the fact that the memory is volatile, it is not possible to get better the programmatically generated records once more and again.

The file handling performs an important position when the data wants to be stored completely into the file. A file is a named vicinity on disk to keep associated information. We can get admission to the stored data (non-volatile) after the program termination.

The file-handling implementation is slightly prolonged or complex in the other programming language, but it is easier and shorter in Python.

In Python, documents are treated in two modes as textual content or binary. The file may be in the textual content or binary format, and every line of a file is ended with the unique character.

Hence, a file operation can be performed in the following order.

Open a file

Read or write – Performing operation

Close the file

Opening a file

Python offers an open() feature that accepts two arguments, file title and get right of entry to mode in which the file is accessed. The feature returns a file object which can be used to perform a number of operations like reading, writing, etc.

Syntax:

file object = open(<file-name>, <access-mode>, <buffering>)     

The documents can be accessed the usage of a number of modes like read, write, or append. The following are the details about the access mode to open a file.

SN Access mode Description
1 r It opens the file to read-only mode. The file pointer exists at the beginning. The file is by default open in this mode if no access mode is passed.
2 rb It opens the file to read-only in binary format. The file pointer exists at the beginning of the file.
3 r+ It opens the file to read and write both. The file pointer exists at the beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The file pointer exists at the beginning of the file.
5 w It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file.
6 wb It opens the file to write only in binary format. It overwrites the file if it exists previously or creates a new one if no file exists. The file pointer exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous file if one exists whereas r+ doesn’t overwrite the previously written file. It creates a new file if no file exists. The file pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The file pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name.
10 ab It opens the file in the append mode in binary format. The pointer exists at the end of the previously written file. It creates a new file in binary format if no file exists with the same name.
11 a+ It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It creates a new file 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 remains at the end of the file.

Let’s look at the simple instance to open a file named “file.txt” (stored in the same directory) in examine mode and printing its content on the console.

Example

#opens the file file.txt in read mode    
fileptr = open("file.txt","r")    
    
if fileptr:    
    print("file is opened successfully")    

Output:

fileobject.close()   

Consider the following example.

# opens the file file.txt in read mode    
fileptr = open("file.txt","r")    
    
if fileptr:    
    print("file is opened successfully")    
    
#closes the opened file    
fileptr.close()  

After closing the file, we can’t function any operation in the file. The file wants to be excellent closed. If any exception occurs whilst performing some operations in the file then the application terminates without closing the file.

We have to use the following approach to overcome such type of problem.

try:  
   fileptr = open("file.txt")  
   # perform file operations  
finally:  
   fileptr.close()  

The with statement

The with statement was once delivered in python 2.5. The with announcement is beneficial in the case of manipulating the files. It is used in the state of affairs the place a pair of statements is to be carried out with a block of code in between.

The syntax to open a file using with the statement is given below.

with open(<file name>, <access mode>) as <file-pointer>:    
    #statement suite     

The benefit of the usage of with statement is that it affords the warranty to close the file regardless of how the nested block exits.

It is continually suggestible to use the with declaration in the case of files because, if the break, return, or exception occurs in the nested block of code then it robotically closes the file, we don’t want to write the close() function. It doesn’t let the file to corrupt.

Consider the following example.

Example

with open("file.txt",'r') as f:    
    content = f.read();    
    print(content)    

Writing the file

To write some textual content to a file, we need to open the file using the open technique with one of the following get admission to modes.

w: It will overwrite the file if any file exists. The file pointer is at the establishing of the file.

a: It will append the existing file. The file pointer is at the cease of the file. It creates a new file if no file exists.

Consider the following example.

Example

# open the file.txt in append mode. Create a new file if no such file exists.  
fileptr = open("file2.txt", "w")  
  
# appending the content to the file  
fileptr.write('''''Python is the modern day language. It makes things so simple. 
It is the fastest-growing programing language''')  
  
# closing the opened the file  
fileptr.close()  

Output:

File2.txt

#open the file.txt in write mode.    
fileptr = open("file2.txt","a")  
    
#overwriting the content of the file    
fileptr.write(" Python has an easy syntax and user-friendly interaction.")    
      
#closing the opened file     
fileptr.close()  

Output:

fileobj.read(<count>)    

Here, the remember is the quantity of bytes to be study from the file beginning from the opening of the file. If the count number is now not specified, then it may additionally read the content of the file till the end.

Consider the following example.

Example

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","r")  
#stores all the data of the file into the variable content    
content = fileptr.read(10)   
# prints the type of the data stored in the file    
print(type(content))      
#prints the content of the file    
print(content)       
#closes the opened file    
fileptr.close()    

Output:

content = fileptr.read()  
print(content)   

Output:

#open the file.txt in read mode. causes an error if no such file exists.    
fileptr = open("file2.txt","r");     
#running a for loop     
for i in fileptr:    
    print(i) # i contains each line of the file     

Output:

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","r");     
#stores all the data of the file into the variable content    
content = fileptr.readline()     
content1 = fileptr.readline()  
#prints the content of the file    
print(content)     
print(content1)  
#closes the opened file    
fileptr.close()    

Output:

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","r");     
    
#stores all the data of the file into the variable content    
content = fileptr.readlines()     
  
#prints the content of the file    
print(content)     
    
#closes the opened file    
fileptr.close()    

Output:

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","x")   
print(fileptr)    
if fileptr:    
    print("File created successfully")  

Output:

# open the file file2.txt in read mode    
fileptr = open("file2.txt","r")    
  
#initially the filepointer is at 0     
print("The filepointer is at byte :",fileptr.tell())    
    
#reading the content of the file    
content = fileptr.read();    
    
#after the read operation file pointer modifies. tell() returns the location of the fileptr.     
    
print("After reading, the filepointer is at:",fileptr.tell())    

Output:

<file-ptr>.seek(offset[, from)    

The seek() method accepts two parameters:

offset: It refers to the new role of the file pointer within the file.

from: It shows the reference role from the place the bytes are to be moved. If it is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the contemporary position of the file pointer is used as the reference position. If it is set to 2, the give up of the file pointer is used as the reference position.

Consider the following example.

Example

# open the file file2.txt in read mode    
fileptr = open("file2.txt","r")    
    
#initially the filepointer is at 0     
print("The filepointer is at byte :",fileptr.tell())    
    
#changing the file pointer location to 10.    
fileptr.seek(10);    
    
#tell() returns the location of the fileptr.     
print("After reading, the filepointer is at:",fileptr.tell())    

Output:

rename(current-name, new-name)    

The first argument is the current file title and the 2d argument is the modified name. We can change the file identify bypassing these two arguments.

Example 1:

import os    
    
#rename file2.txt to file3.txt    
os.rename("file2.txt","file3.txt")  

Output:

remove(file-name)   

Example 1

import os;    
#deleting the file named file3.txt     
os.remove("file3.txt")    

Creating the new directory

The mkdir() method is used to create the directories in the modern working directory. The syntax to create the new directory is given below.

Syntax:

mkdir(directory name)  

Example 1

import os    
    
#creating a new directory with the name new    
os.mkdir("new")    

The getcwd() method

This method returns the cutting-edge working directory.

The syntax to use the getcwd() method is given below.

Syntax

os.getcwd()  

Example

import os  
os.getcwd()  

Output:

chdir("new-directory")    

Example

import os   
# Changing current directory with the new directiory  
os.chdir("C:\\Users\\DEVANSH SHARMA\\Documents")  
#It will display the current working directory  
os.getcwd()  

Output:

os.rmdir(directory name)    

Example 1

import os  
#removing the new directory     
os.rmdir("directory_name")    

It will remove the specified directory.

Writing Python output to the files

In Python, there are the necessities to write the output of a Python script to a file.

The check_call() method of module subprocess is used to execute a Python script and write the output of that script to a file.

The following example consists of two python scripts. The script file1.py executes the script file.py and writes its output to the textual content file output.txt.

Example

file.py

temperatures=[10,-20,-289,100]    
def c_to_f(c):    
    if c< -273.15:    
        return "That temperature doesn't make sense!"    
    else:    
        f=c*9/5+32    
        return f    
for t in temperatures:    
    print(c_to_f(t))    

file.py

import subprocess    
    
with open("output.txt", "wb") as f:    
    subprocess.check_call(["python", "file.py"], stdout=f)    

The file related methods

The file object offers the following methods to manipulate the documents on various running systems.

SN Method Description
1 file.close() It closes the opened file. The file once closed, it can’t be read or write anymore.
2 File.fush() It flushes the internal buffer.
3 File.fileno() It returns the file descriptor used by the underlying implementation to request I/O from the OS.
4 File.isatty() It returns true if the file is connected to a TTY device, otherwise returns false.
5 File.next() It returns the next line from the file.
6 File.read([size]) It reads the file for the specified size.
7 File.readline([size]) It reads one line from the file and places the file pointer to the beginning of the new line.
8 File.readlines([sizehint]) It returns a list containing all the lines of the file. It reads the file until the EOF occurs using readline() function.
9 File.seek(offset[,from) It modifies the position of the file pointer to a specified offset with the specified reference.
10 File.tell() It returns the current position of the file pointer within the file.
11 File.truncate([size]) It truncates the file to the optional specified size.
12 File.write(str) It writes the specified string to a file
13 File.writelines(seq) It writes a sequence of the strings to a file.

Deleting directory

The rmdir() approach is used to delete the distinct directory.

The syntax to use the rmdir() technique is given below.

Syntax

Changing the current working directory

The chdir() method is used to alternate the current working directory to a designated directory.

The syntax to use the chdir() technique is given below.

Syntax

The above code renamed present day file2.txt to file3.txt

Removing the file

The os module presents the remove() approach which is used to put off the special file. The syntax to use the remove() method is given below.

Python OS module

Renaming the file

The Python os module permits interaction with the operating system. The os module affords the functions that are worried in file processing operations like renaming, deleting, etc. It presents us the rename() technique to rename the detailed file to a new name. The syntax to use the rename() approach is given below.

Syntax:

Modifying file pointer position

In real-world applications, once in a while we need to alternate the file pointer location externally on account that we can also want to examine or write the content at quite a number locations.

For this purpose, the Python offers us the seek() approach which allows us to regulate the file pointer position externally.

The syntax to use the seek() technique is given below.

Syntax:

File Pointer positions

Python presents the tell() technique which is used to print the byte wide variety at which the file pointer presently exists. Consider the following example.

Creating a new file

The new file can be created by the usage of one of the following access modes with the feature open().

x: it creates a new file with the exact name. It causes an error a file exists with the equal name.

a: It creates a new file with the precise name if no such file exists. It appends the content to the file if the file already exists with the detailed name.

w: It creates a new file with the specific title if no such file exists. It overwrites the existing file.

Consider the following example.

Example 1

We called the readline() function two instances that is why it read two strains from the file.

Python presents also the readlines() approach which is used for the studying lines. It returns the list of the lines till the end of file(EOF) is reached.

Example 2: Reading Lines Using readlines() characteristic

Read Lines of the file

Python facilitates to examine the file line by using line with the aid of the use of a feature readline() method. The readline() approach reads the strains of the file from the beginning, i.e., if we use the readline() method two times, then we can get the first two traces of the file.

Consider the following instance which includes a function readline() that reads the first line of our file “file2.txt” containing three lines. Consider the following example.

Example 1: Reading lines the use of readline() function

Read file through for loop

We can examine the file the use of for loop. Consider the following example.

In the above code, we have read the content of file2.txt by using using the read() function. We have passed rely price as ten which ability it will study the first ten characters from the file.

If we use the following line, then it will print all content of the file.

Snapshot of the file2.txt

We can see that the content of the file is modified. We have opened the file in a mode and it appended the content material in the current file2.txt.

To read a file the use of the Python script, the Python offers the read() method. The read() technique reads a string from the file. It can examine the facts in the text as nicely as a binary format.

The syntax of the read() method is given below.

Syntax:

Snapshot of the file2.txt

We have opened the file in w mode. The file1.txt file would not exist, it created a new file and we have written the content material in the file the usage of the write() function.

Example 2

In the above code, we have surpassed filename as a first argument and opened file in examine mode as we cited r as the 2d argument. The fileptr holds the file object and if the file is opened successfully, it will execute the print assertion

The close() method

Once all the operations are finished on the file, we should shut it through our Python script using the close() method. Any unwritten information receives destroyed once the close() technique is referred to as on a file object.

We can operate any operation on the file externally the use of the file device which is the presently opened in Python; therefore it is good practice to shut the file as soon as all the operations are done.

The syntax to use the close() approach is given below.

Syntax