File Handling In Python

Introduction

 
In this article, I will explain about file handling in Python.
 
Definition
 
File handling has some functions for creating, reading, updating, and deleting files.
 

File handling

 
In Python, open () two parameters. One parameter is reporting name and any other parameter is mode. There are four forms of mode. There are:
  1. “r” =read () is used for reading the file.
  2. “a” =append () is used to append the file (append mode)
  3. “w” =write () is used to write the file (write mode)
  4. “r+” ==read () and write () mode are used in the file handling.
  5. “t” - t is text mode
  6. “b” - b is binary mode
Syntax
  1. f=open(“filename.txt”)  
(or)
  1. f=open(“filename.txt”,“rt”)   
Both are same because “r” is default mode and read mode, “t” is default mode and text mode
 

Open file and read mode

 
To open the file used keyword open (). The read () method for reading the file.
 
Example
  1. f=open("F:/download surya/demo.txt","r"#file name and mode  
  2. print(f.read())# read mode  
Output
 
Simple read mode program.
 
File Handling In Python
 

Read only part of the File

 
In Python, the read method returns the whole text. We can also specify how many letters you want to return.
 
Example
  1. f=open("F:/download surya/demo.txt","r"#file name and mode  
  2. print(f.read(2)) # how many letters you want to return.  
Output
 
Return the first 2 letters in the file.
 
File Handling In Python
 

Read lines

 
In python, we can return first (or) one line by using the readline () method keyword.
 
Example
  1. f=open("F:/download surya/demo.txt","r")#read mode  
  2. print(f.readline())#Return first line in the output screen.  
Output
 
Return one line in the output screen.
 
File Handling In Python
 

Loop in file

 
In Python, looping through the lines of the file, we can read the whole file, one by one.
 
Example
  1. f=open("F:/download surya/demo.txt","r")#read mode  
  2. for x in f:# Return the file one by one.  
  3.   print(x)  
Output
 
Return the file one by one.
 
File Handling In Python
 

Close files

 
In Python, we want to close the file when you complete the work using the close () method keyword.
 
Example
  1. f=open("F:/download surya/demo.txt","r")#read mode  
  2. print(f.read())  
  3. f.close()# close() method is to close the file
Output
 
Close the file when you are finished with your work.
 
File Handling In Python
 

Conclusion

 
In this article, we have seen file handling in Python. I hope this article was useful to you. Thanks for reading.


Recommended Free Ebook
Similar Articles