# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. For operations on individual files.

import shutil

print(dir(shutil))

# **shutil.copyfileobj(fsrc, fdst[, length])** - method in Python is used to copy the contents of a file-like object to antoher file-like object. By default this method copy data in chunks and if want we can also specify the buffer size through length parameter.
# This method copies the content of the file from the current file position to the end of the file

import shutil
source = 'file.txt'
fsrc = open(source, 'r')
dest = 'file_copy.txt'
fdst = open(dest, 'w')
shutil.copyfileobj(fsrc, fdst)
print("Contents of the file object copied sucessfully")
fsrc.close()
fdst.close()

# **shutil.copyfile(src, dst, *, follow_symlinks=True)** - Copy the contents (no metadata) of the file named src to a file named dst and return dst in the most efficient way possible. src and dst are path-like objects or path names given as strings

import shutil
import os
import glob
print(os.listdir())
resp = shutil.copyfile('file.txt', 'file2.txt')
print(f"The response is - {resp}")
print(os.listdir())

# **shutil.copymode()** - It is used to copy the permission bits from the given source path to given destination path. The shutil.copymode() method does not affect the file content or owner and group information

print(glob.glob('*'))
src = 'app.py'
dest = 'file.txt'
print(f"Permission bits of source: {oct(os.stat(src).st_mode)[-3:]}")
print(f"Permission bits of source: {oct(os.stat(dest).st_mode)[-3:]}")
# shutil.copymode(src, dest)
# print(f"Permission bits of source: {oct(os.stat(dest).st_mode)[-3:]}")

# **shutil.copystat(source, destination, *, follow_symlinks = True)** - It is used to copy the permission bits, last access time, last modification time and flags value from the given source path to given destination. This method does not affect the file content and owner and group info

# +
import time
src = 'basicLogging.py'
dest = 'file2.txt'
print("Before using shutil.copystat() method:") 
print("Source metadata:") 
print("Permission bits:", oct(os.stat(src).st_mode)[-3:]) 
print("Last access time:", time.ctime(os.stat(src).st_atime)) 
print("Last modification time:", time.ctime(os.stat(src).st_mtime)) 
print("--------------------------------------------------------------")
print("\nDestination metadata:") 
print("Permission bits:", oct(os.stat(dest).st_mode)[-3:]) 
print("Last access time:", time.ctime(os.stat(dest).st_atime)) 
print("Last modification time:", time.ctime(os.stat(dest).st_mtime))



shutil.copystat(src, dest)
print("\nDestination metadata:") 
print("Permission bits:", oct(os.stat(dest).st_mode)[-3:]) 
print("Last access time:", time.ctime(os.stat(dest).st_atime)) 
print("Last modification time:", time.ctime(os.stat(dest).st_mtime))

# -

# **shutil.copy(src,dst, *, follow_symlinks=True)** - Copies the file src to the file or directory dst. src and dst should be path-like objects or strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file.

import glob
glob.glob('*')

import os
os.mkdir('Test')

import shutil
shutil.copy('app.py', 'Test')

shutil.copy('app.py', 'yoyo.txt')

# **shutil.copy2(src, dst, *, follow_symlinks=True)** - Identical to copy except that copy2() also attempts to preserve file metadata.

shutil.copy2('app.py', 'yoyoyo.txt')

shutil.__all__

# **shutil.ignore_patterns(*patterns)** - This factory function creates a function that can be used as a callable for copytree()'s ignore argument, ignoring files and directories that match one of the glob-style patterns provided

# **shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)** - Recursively copy an entire directory tree rooted at src to a directory named dst and returned the destination directory. dir_exists_ok dictates whether to raise an exception in case dst or any missing parent directory already exists.

import os
import glob
import shutil
if os.path.isdir('ToTest'):
    os.rmdir('ToTest')
else:
    os.mkdir("ToTest")
shutil.copytree(os.path.abspath(''), os.path.abspath('ToTest'), ignore=shutil.ignore_patterns('.ipynb_checkpoints'))

os.path.abspath('')

os.listdir()

# **shutil.rmtree(path, ignore_errors=False, onerror=None)** - Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory)

for i in os.listdir():
    if os.path.isdir(i):
        print(i)

os.rmdir('ToTest')

shutil.rmtree('ToTest')

# **shutil.move(src, dst, copy_function=copy2)** - Recursively move a file or directory (src) to another location (dst) and return the destination.

src = glob.glob('*')
dst = os.path.split(os.path.abspath(''))[0]
shutil.move(os.path.abspath('Test'), os.path.split(os.path.abspath(''))[0])

os.path.abspath('Test')

os.mkdir(f"{os.path.split(os.path.abspath(''))[0]}\\TOTESTYO")

os.path.split(os.path.abspath(''))[0]

# **shutil.disk_usage(path)** - Return disk usage statistics about the given path as a named tuple with the attributes total, used and free, which are the amount of total, used and free space, in bytes. Path may be a file or a directory

shutil.disk_usage('C:')

# **shutil.chown(path, user=None, group=None)** - Change owner user and/or group of the given path

import os
import glob
import shutil
from pathlib import Path

os.listdir()

# +
path = 'app.py'

info = Path(path)
user = info.owner()
group = info.group()

print("Current owner and group of the specified path")  
print("Owner:", user) 
print("Group:", group) 
# -

# **shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None)** - Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return None.

print(shutil.which('python'))
print(shutil.which('gcc'))
print(shutil.which('git'))

# **exception shutil.Error** - This exception collects exception that are raised during a multi-line operation. FOr copytree() the exception argument is a list of 3-tuples (srcname, dstname, exception)

# # Archiving Operations
#
# **shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])** - Create an archive file (such as zip or tar) and return its name

shutil.make_archive('Archive_Test', 'zip')

archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))

archive_name

os.path.expanduser(os.path.join('~', '.ssh'))

# **shutil.get_archive_formats()** - Return a list of supported formats for archivomg. Each elements of the returned sequence is a tuple (name, description)

import os
import glob
import shutil
os.listdir()

shutil.get_archive_formats()


# **shutil.register_archive_format(name, function[, extra_args[, description]])** - Register an archiver for the format name.

def myzip():
    pass
shutil.register_archive_format('myzip', myzip, description='myzip file')
shutil.get_archive_formats()

# **shutil.unregister_archive_format(name)** - Remove the archive format name from the list of supported formats.

shutil.unregister_archive_format('myzip')
shutil.get_archive_formats()

# **shutil.unpack_archive(filename[, extract_dir[, format]])** - Unpack an archive. filename is the full path of the archive.

shutil.unpack_archive(os.path.abspath('file.zip'), 'C:\\Users\\<NAME>\\Standard Library\\FORTESTYO', 'zip')


# **shutil.register_unpack_format(name, extensions, function[, extra_args[, description]])** - register an un[acl format. name is the name of the format and extensions is a list of extensions corresponding to the format like `.zip` for Zip file

def yoyo():
    pass
shutil.register_unpack_format('yoyo', '[.yoyo]', yoyo, description='yoyo')
shutil.get_unpack_formats()

# **shutil.unregister_unpack_format(name)** - Unregister an unpack format. name is the name of the formnat

shutil.unregister_unpack_format('yoyo')
shutil.get_unpack_formats()

# **shutil.get_unpack_formats()** - Return a list of all registered formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description).

shutil.get_unpack_formats()

# # Querying the size of the output terminal
# **shutil.get_terminal_size(fallback=(columns, lines))** - Get the size of the terminal window

shutil.get_terminal_size()

StarcoderdataJupyterScriptsDedupFiltered