shutil()

shutil module provides us a number of high-level operations on files. We can copy and remove files and directories. Let’s get started with the module and learn the practical implementation of each of the files in detail.

Reference : shutil-High-level file operations official docs

Copy Files

import shutil
 
f=open('data.txt','r')
f1=open('data1.txt','w')
 
# Syntax: shutil.copyfileobj(src,dst)
shutil.copyfileobj(f,f1)
 
f.close()
f1.close()
import shutil
#shutil.copy(src.dst)
shutil.copy('data.txt','data1.txt')

Move(src,dst)

import shutil
import os
 
path='D:\DSCracker\DS Cracker'
print("Source folder:") 
print(os.listdir(path))
 
path1='D:\DSCracker\DS Cracker\Python'
shutil.move('shutil.py','Python')
 
print("After moving file shutil.py to destination folder, destination contains:") 
print(os.listdir(path1))
Source folder:
['cs', 'data.txt', 'Python', 'ReverseArray', 'ReverseArray.cpp', 'shutil.py']
After moving file shutill.py to destination folder, destination contains:
['data1.txt', 'data3.txt', 'hey.py', 'nsawk.py', 'shutil.py']

disk_usage(path)

import shutil
import os
 
path = 'D:\\DSCracker\\DS Cracker\\NewPython\\python1'
 
statistics=shutil.disk_usage(path)
 
print(statistics)

# usage(total=1000203087872, used=9557639168, free=990645448704)

Which()

import shutil
import os
 
cmd='Python'
 
locate = shutil.which(cmd) 
 
print(locate)

# C:\Users\AskPython\AppData\Local\Microsoft\WindowsApps\Python.EXE

Last updated