File Handling In Python

Introduction

 
In this chapter, you will learn about file handling in Python.
 

File handling

 
File handling has some functions for creating, reading, updating, and deleting files.
 
In Python, open () two parameters. One parameter is reporting name and any other parameter is the 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 a 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 the default mode and read mode, “t” is the 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 the next chapter, we will discuss OOPs concepts.
Author
Surya S
428 3.6k 645.6k
Next » Python Object Oriented Programming Concepts