Python File Handling

Table Of Contents:

  1. What Is A File?
  2. What Is File Handling?
  3. Check Whether The File
  4. Exist Or Not.
  5. How To Open Files In Python?
  6. Modes Of File Operation.
  7. How To Close Files In Python?
  8. How To Write Inside A File In Python?
  9. How To Read Files In Python?
  10. How To Delete A File In Python?
  11. How To Delete An Empty Folder In Python?
  12. How To Delete A Folder Containing Files In Python?

(1) What Is A File?

  • To store data or information permanently into your hard drive we generally use files.
  • Files are the place where you write your information inside it.
  • Your resume is a file where you store your experience details.

(2) What Is File Handling?

  • When we want to read from or write to a file, we need to open it first.
  • When we are done, it needs to be closed so that the resources that are tied with the file are freed.
  • Hence, in Python, a file operation takes place in the following order:
    (1) Open A File.
    (2) Read or Write (perform operation).
    (3) Close The File.

(3) Check Whether The File Exist or Not.

  • Before you do any operation on files, first you should check whether the file exist at that particular location or not.
  • If the file exist you are good to go or else you have to inform user file does not exist.
  • exists() method is used to check whether the file exists or not.

Syntax:

from os.path import exists

exists(file_path)
  • exists() method takes file path as an argument and returns True if file exist else return False.
  • Returns:
  • True: If File Exist
  • False: If File Does Not Exist.

Example-1

from os.path import exists

file_path = "E:\Blogs\Python\demofile.txt"

file_exists = exists(file_path)

if file_exists:
    print('File Exists')
else:
    print("File Does Not Exists")
Output:
File Exists

Example-2

from os.path import exists

file_path = "E:\Blogs\Python\nofile.txt"

file_exists = exists(file_path)

if file_exists:
    print('File Exists')
else:
    print("File Does Not Exists")
Output:
File Does Not Exists

(4) How To Open Files In Python?

  • open() method is used to open files in python.
  • open() method returns a file object, also called a handle.
  • You can use this file object to read or modify the file accordingly.

Syntax:

open(file_path)
  • Input: File Path
  • Returns: File Object

Example-1

file_path = "E:\Blogs\Python\demofile.txt"

file = open(file_path)

print(file)
Output:
<_io.TextIOWrapper name='E:\\Blogs\\Python\\demofile.txt' mode='r' encoding='cp1252'>

(5) Modes Of File Operation.

  • We can specify the mode while opening a file.
  • In mode, we specify whether we want to read r, write w or append a to the file.
  • We can also specify if we want to open the file in text mode or binary mode.
  • The default is reading in text mode. In this mode, we get strings when reading from the file.
  • On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like images or executable files.

(6) How To Close Files In Python.

  • It is the best practice to close the files, after you finished your operations on files.
  • It will free up the resources allocated to that file.
  • close() method is used to close the files in Python.
  • Python has a garbage collector to clean up unreferenced objects but we must not rely on it to close the file.

Syntax:

<file_object>.colse()
  • You can call close() method on your file object.

Example-1

file_path = "E:\Blogs\Python\demofile.txt"

file = open(file_path) #Opening The File

file.close() #Closing The File
  • This method is not entirely safe.
  • If an exception occurs when we are performing some operation with the file, the code exits without closing the file.

Example-2

try:
    file_path = "E:\Blogs\Python\demofile.txt"
    
    file = open(file_path)
    
finally:
    file.close()
  • The best way to close a file is by using the with statement. This ensures that the file is closed when the block inside the with statement is exited.
  • We don’t need to explicitly call the close() method. It is done internally.

Example-3

with open("E:\Blogs\Python\demofile.txt") as file:
   # perform file operations

(7) How To Write Inside Files In Python?

  • To write inside a file in Python we need to open it in write w, append a or exclusive creation x mode.
  • Be careful with the w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.
  • Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

Example

with open("E:\Blogs\Python\demofile.txt",'w',encoding = 'utf-8') as file:
    file.write("My Name Is Subrat Kumar Sahoo\n")
    file.write("I Am From India\n")
    file.write("I Likes To Write Blogs\n")

Before: Empty File

After: Written Text

(8) How To Read Files In Python?

  • To read a file in Python, we must open the file in reading r mode.
  • read() method is used to read the values present inside file.
  • We can use the read(size) method to read in the size number of data.
  • If the size parameter is not specified, it reads and returns up to the end of the file.

Example:Reading The demo.txt File

with open("E:\Blogs\Python\demofile.txt",'r',encoding = 'utf-8') as file:
    
    print(file.read(8)) # read the first 8 data
    
    print(file.read(3)) # read the next 4 data
    
    print(file.read()) # read in the rest till end of file
    
    print(file.read()) # further reading returns empty sting
Output:
My Name 
Is 
Subrat Kumar Sahoo
I Am From India
I Likes To Write Blogs

(9) How To Delete A File In Python?

  • remove() method is used to delete permanently your file from hard drive.
  • You can remove unnecessary files present inside a folder by using remove() method.
  • You must import the OS module, and run its os.remove() function.

Syntax:

os.remove(file_path)

Example:

import os

os.remove("E:\Blogs\Python\demofile.txt")

(10) How To Delete An Empty Folder In Python?

  • os.rmdir() method is used to remove an empty folder from your hard drive.

Syntax:

os.rmdir(file_path)

Example:

import os

os.rmdir("E:\Blogs\EmptyFolder")

Before: Empty Folder

After: Deleted Folder

(11) How To Delete A Folder Containing Files In Python?

  • shutil.rmtree() is used to delete an entire directory containing folders and files inside it.

Syntax:

shutil.rmtree(path, ignore_errors=False, onerror=None) 

Parameters:

  • path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
  • ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.
  • oneerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.

Example:

import shutil
import os

shutil.rmtree("E:\Blogs\Content")

Leave a Reply

Your email address will not be published. Required fields are marked *