Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I copy a binary file in Python?
In Python, you may need to duplicate binary files such as images, videos, or executables. This article explores efficient methods for copying binary files in Python, covering both built-in functions and manual approaches.
What is Binary Format?
Binary format stores data as raw byte sequences (0s and 1s) rather than readable text characters. Binary file copying duplicates files byte-by-byte without interpreting content, essential for non-text files like images (.jpg, .png), audio/video (.mp3, .mp4), executables (.exe), and PDFs.
Using shutil.copy()
The shutil.copy() function copies file contents and basic permissions from source to destination ?
Syntax
import shutil shutil.copy(src, dst)
Parameters:
- src: Path to the source file
- dst: Path to the destination file or directory
Example
import shutil
import os
# Create a sample binary file for demonstration
with open("sample.txt", "wb") as f:
f.write(b"Binary content example\x00\x01\x02")
source = "sample.txt"
destination = "sample_copy.txt"
try:
shutil.copy(source, destination)
print("File copied successfully.")
# Verify copy
if os.path.exists(destination):
print(f"File size: {os.path.getsize(destination)} bytes")
except FileNotFoundError:
print("Source file not found.")
except PermissionError:
print("Permission denied.")
File copied successfully. File size: 26 bytes
Using shutil.copyfile()
shutil.copyfile() copies only file contents without metadata or permissions, performing direct byte-for-byte copying ?
Example
import shutil
source = "sample.txt"
destination = "sample_copyfile.txt"
try:
shutil.copyfile(source, destination)
print("File copied successfully.")
# Read and verify binary content
with open(destination, "rb") as f:
content = f.read()
print(f"Content: {content}")
except FileNotFoundError:
print("Source file not found.")
except PermissionError:
print("Permission denied.")
File copied successfully. Content: b'Binary content example\x00\x01\x02'
Using open() in Binary Mode
Manual copying using open() with binary modes ('rb' and 'wb') gives complete control over the copying process ?
Example
source = "sample.txt"
destination = "sample_manual.txt"
try:
with open(source, 'rb') as src_file, open(destination, 'wb') as dst_file:
data = src_file.read()
dst_file.write(data)
print("File copied successfully.")
# Verify byte-by-byte copy
with open(source, 'rb') as f1, open(destination, 'rb') as f2:
print(f"Files identical: {f1.read() == f2.read()}")
except FileNotFoundError:
print("Source file not found.")
except PermissionError:
print("Permission denied.")
File copied successfully. Files identical: True
Using shutil.copy2()
shutil.copy2() copies file contents, permissions, and preserves metadata like timestamps ?
Example
import shutil
import os
source = "sample.txt"
destination = "sample_copy2.txt"
try:
# Get original file stats
original_stats = os.stat(source)
shutil.copy2(source, destination)
print("File copied successfully with metadata.")
# Compare timestamps
new_stats = os.stat(destination)
print(f"Timestamps preserved: {abs(original_stats.st_mtime - new_stats.st_mtime) < 1}")
except FileNotFoundError:
print("Source file not found.")
except PermissionError:
print("Permission denied.")
File copied successfully with metadata. Timestamps preserved: True
Comparison
| Method | Copies Permissions? | Preserves Metadata? | Best For |
|---|---|---|---|
shutil.copy() |
Yes | No | General copying |
shutil.copyfile() |
No | No | Content-only copying |
open() binary |
No | No | Custom copying logic |
shutil.copy2() |
Yes | Yes | Complete duplication |
Conclusion
Use shutil.copy2() for complete file duplication with metadata preservation. Use shutil.copy() for standard copying needs. Use manual open() with binary modes when you need custom copying logic or handling large files in chunks.
