how to use python shutil module for high level operations - python shutil module complete tutorial

Namaste Friends,


Today, In this tutorial i am going to show you how to use python shutil module? or you can say complete shutil module tutorial!.


Basic queries


Python Shutil Module


Python Shutil Module provide us a number of high-level operation on files and folders. In Simple Word, Shutil module functions give us some high-level files and folder related operation capabilities.
like copy, move, remove and much more.



So, let's start our practical example.

Python Shutil Module Practical Examples.




shutil_tutorial_part_1 slides
In [1]:
#!/usr/bin/python
#
# ============================================
#       PYTHON SHUTIL MODULE TUTORIAL
# ============================================
#
# Author : SSB
#          surajsinghbisht054@gmail.com
#          https://bitforestinfo.blogspot.com
# 
#
# Here, I am Using
# 
# Operating System : Ubuntu 16.04 LTS
# Python Version   : 2.7.12
# Editor           : ipython notebook
#
#
In [2]:
#
# Import module
#
import shutil
import os
import StringIO
In [3]:
# 
# Here, For This Example, We will create new files and
# folders
#
# List Of Folders Available In Current Folder
#
print "[1] List Of Folders"

print '[2]', os.listdir(".")
#
# Make 2 Folder
#
# first folder name = test_1
#
print "[3] Creating Folder... test_1"

os.mkdir("test_1")
#
# Second Folder name = test_2

print "[4] Creating Another folder .. test_2"

os.mkdir("test_2")

# Now Check Again Current Directory

print "[5] Again, List of Folders in current directory"

print '[6]',os.listdir(".")


# Create 2 files in test_1 folder

# first file

print "[7] First file created in test_1 folder"

open("test_1/test_file_1.txt",'w').close()

# second file

print "[8] Second file created in test_1 folder"

open("test_1/test_file_2.txt",'w').close()

# check list of files in test_1 folder

print "[9] ",os.listdir("test_1/")
[1] List Of Folders
[2] ['.ipynb_checkpoints', 'shutil_tutorial_part_1.ipynb']
[3] Creating Folder... test_1
[4] Creating Another folder .. test_2
[5] Again, List of Folders in current directory
[6] ['.ipynb_checkpoints', 'shutil_tutorial_part_1.ipynb', 'test_2', 'test_1']
[7] First file created in test_1 folder
[8] Second file created in test_1 folder
[9]  ['test_file_2.txt', 'test_file_1.txt']
In [4]:
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# shutil.copyfile(file_src, file_dest)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Copy data of from source file
# to the file destination.
#
#
# Example Text
#

print "Before Copy 'test_2/' :", os.listdir("test_2/")
#
shutil.copyfile("test_1/test_file_1.txt", "test_2/test_file_1.txt.copy")
#
#
print "After Copy 'test_2/' :", os.listdir("test_2/")
Before Copy 'test_2/' : []
After Copy 'test_2/' : ['test_file_1.txt.copy']
In [5]:
#
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# shutil.copyfileobj(file_src, file_dst)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Copy data of the file like object file source
# to the file like object file destination.
#
# 
example_text = """
This is an example text.

Here, I am trying to show you

how to use python shutil module
"""
#
# Create 2 File Like Object 
#
# Input file like object
file_like_obj_1 = StringIO.StringIO(example_text)
#
# output file like object
file_like_obj_2 = StringIO.StringIO()

#
# Now, Copy data
shutil.copyfileobj(file_like_obj_1, file_like_obj_2)
In [6]:
#
# print copied data
#
file_like_obj_2.seek(0)
#
# print data
#
print file_like_obj_2.read()
This is an example text.

Here, I am trying to show you

how to use python shutil module

In [7]:
#
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# shutil.copymode(file_src, file_dst)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# With This Command, You Can Copy the permission bits from 
# source file to destination file. The file contents, Permission, 
# owner, and group are unaffected. 
#
#

# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# shutil.copystat(file_src, file_dst)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# With THis Command, You Can Copy the Permission bits,
# last modification time, last access time, flag
# and other information from source file to
# destination file. The Source file contents and another
# data are unaffected.

# print file stats
print "Before Source File      : ", os.stat("test_1/test_file_1.txt").st_ctime
print "Before Destination File : ", os.stat("test_2/test_file_1.txt.copy").st_ctime

shutil.copystat("test_1/test_file_1.txt", "test_2/test_file_1.txt.copy")

# print file stats
print "After Source File      : ", os.stat("test_1/test_file_1.txt").st_ctime
print "After Destination File : ", os.stat("test_2/test_file_1.txt.copy").st_ctime
Before Source File      :  1492595638.23
Before Destination File :  1492595638.4
After Source File      :  1492595638.23
After Destination File :  1492595638.79
In [8]:
#
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# shutil.copy(file_src, file_dst)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Copy file from Source to the file or directory destination.
# Permission bits are also copied. (shutil.copymode function)
#
#
# Let's me show you a example.
# In this example, i will copy "test_file_1.txt" file
# data from "test_1" folder to "test_2" folder.
#
print os.listdir("test_1/")

print os.listdir("test_2/")

shutil.copy("test_1/test_file_2.txt", "test_2/")
['test_file_2.txt', 'test_file_1.txt']
['test_file_1.txt.copy']
In [9]:
#
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# shutil.copy2(src, dst)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# this is just shutil.copy() followed by copystat().
#
#

print os.listdir("test_1/")

print os.listdir("test_2/")

shutil.copy2("test_1/test_file_1.txt", "test_2/")
['test_file_2.txt', 'test_file_1.txt']
['test_file_1.txt.copy', 'test_file_2.txt']
In [10]:
#
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# shutil.copytree(src, dst)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Copy an entire directory tree rooted at src to the
# destination directory, named by dst
#
#
shutil.copytree('test_2', "test/")
In [11]:
#
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# shutil.move(file_src, file_dst)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Move a file or directory (src) to another location (dst).
#
#
print "Before : ", os.listdir('.')
shutil.move('test_2/', "test_1/")
print "After  : ", os.listdir(".")
Before :  ['.ipynb_checkpoints', 'shutil_tutorial_part_1.ipynb', 'test', 'test_2', 'test_1']
After  :  ['.ipynb_checkpoints', 'shutil_tutorial_part_1.ipynb', 'test', 'test_1']
In [12]:
#
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# shutil.rmtree(path)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Delete an entire directory tree
#
print "Before : ", os.listdir('.')
shutil.rmtree("test_1/")
print "After  : ", os.listdir('.')
shutil.rmtree("test/")
Before :  ['.ipynb_checkpoints', 'shutil_tutorial_part_1.ipynb', 'test', 'test_1']
After  :  ['.ipynb_checkpoints', 'shutil_tutorial_part_1.ipynb', 'test']
In [13]:
print os.listdir(".")
['.ipynb_checkpoints', 'shutil_tutorial_part_1.ipynb']
In [14]:
# Reference
#
# -------------------------------------------------------------------------
# | Function          |Copies Metadata|Copies Permissions|Can Specify Buffer|
# -------------------------------------------------------------------------
# | shutil.copy       |      No       |        Yes       |        No        |
# -------------------------------------------------------------------------
# | shutil.copyfile   |      No       |         No       |        No        |
# -------------------------------------------------------------------------
# | shutil.copy2      |     Yes       |        Yes       |        No        |
# -------------------------------------------------------------------------
# | shutil.copyfileobj|      No       |         No       |       Yes        |
# -------------------------------------------------------------------------
In [15]:
# So, Friends, Today Tutorials Ends Here.
# But Friends, Don't Worry, In Next Tutorial.
# i will show you more interesting topic.
#
#
# Python Official Website:
#         https://docs.python.org/2/library/datetime.html
#
#



Thanks For Reading,

If you like our blog,
then don't forget to subscribe,
comment and share.


Have a wonderful day!

Share this

Related Posts

Previous
Next Post »