Skip to content

Instantly share code, notes, and snippets.

@mraza007
Last active November 10, 2023 05:44
Show Gist options
  • Save mraza007/ed52c94d7ef70dba9c5658b6fb5ba5ab to your computer and use it in GitHub Desktop.
Save mraza007/ed52c94d7ef70dba9c5658b6fb5ba5ab to your computer and use it in GitHub Desktop.
cp command implemented using python
import os
import sys
def copy(src: str, dest: str) -> None:
"""
Copy the contents of the source file to the destination file or directory.
If dest is a directory, the file will be copied into it with the same filename.
Args:
src (str): The path to the source file.
dest (str): The path to the destination file or directory.
Raises:
FileNotFoundError: If the source file does not exist or is not a file.
IsADirectoryError: If the destination is a directory but the filename is not provided.
"""
# Ensure the source file exists and is a file
if not os.path.isfile(src):
raise FileNotFoundError(f"Source file {src} not found or is not a file.")
# Check if destination is a directory
if os.path.isdir(dest):
# Construct the full file path by joining the directory with the basename of the source file
dest = os.path.join(dest, os.path.basename(src))
# Open the source file in binary read mode and destination file in binary write mode
with open(src, "rb") as fsrc, open(dest, "wb") as fdst:
# Read the source file content in chunks
while True:
chunk = fsrc.read(1024) # Read in 1KB chunks
if not chunk:
break
fdst.write(chunk)
# Command-line interface
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python script.py source_file destination_path")
sys.exit(1)
source_path = sys.argv[1]
destination_path = sys.argv[2]
try:
copy(source_path, destination_path)
print(f"Copied {source_path} to {destination_path}")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment