Objective
Develop a Python program that duplicates a source file to a target file using FileStream and processes the file in 512 KB blocks. For example, if you input the following:
`mycopy file.txt e:\file2.txt`
The program should properly handle scenarios where the source file is missing and should notify the user if the destination file exists (without overwriting it).
Example Python Exercise
Show Python Code
# Python program to duplicate a source file to a target file in 512 KB blocks
def copy_file(source_path, target_path):
try:
# Check if the source file exists
with open(source_path, 'rb') as source_file:
# Check if the destination file exists
try:
with open(target_path, 'xb') as target_file:
# Process the file in 512 KB blocks
buffer_size = 512 * 1024 # 512 KB
while chunk := source_file.read(buffer_size):
target_file.write(chunk)
print(f"File copied successfully to {target_path}")
except FileExistsError:
print(f"Error: The target file '{target_path}' already exists. Please choose a different name.")
except FileNotFoundError:
print(f"Error: The source file '{source_path}' does not exist.")
# Example usage
copy_file("file.txt", "e:\\file2.txt")
Output
File copied successfully to e:\file2.txt
Share this Python Exercise