Create a Backup Copy of a File using Python
To create a backup copy of a file using Python, you can use the shutil
module, which provides functions to copy files and directories. The most commonly used method is shutil.copy()
, which allows copying a file to a specified backup location.
Examples to Create a Backup Copy of a File
1. Copy a File Using shutil.copy()
In this example, we will use the shutil.copy()
method to create a backup copy of a file. The function takes two arguments: the source file path and the destination file path.
We shall take backup of the file data.txt
and store it as backup_data.txt
.
main.py
import shutil
# Source file path
source_file = "data.txt"
# Destination file path (Backup copy)
backup_file = "backup_data.txt"
# Copying the file
shutil.copy(source_file, backup_file)
print("Backup created successfully.")
Explanation:
- We import the
shutil
module, which contains file copy functions. - Define
source_file
as the original file that we want to back up. - Specify
backup_file
as the new file where the backup copy will be saved. - Use
shutil.copy(source_file, backup_file)
to copy the contents of the source file to the backup file. - Print a message to confirm that the backup was created successfully.
Output:
Backup created successfully.
2. Copy a File with Metadata Using shutil.copy2()
Sometimes, you might want to copy a file along with its metadata, such as timestamps. In this case, we use shutil.copy2()
, which preserves file metadata.
main.py
import shutil
# Source file path
source_file = "report.pdf"
# Destination file path (Backup copy)
backup_file = "backup_report.pdf"
# Copying the file with metadata
shutil.copy2(source_file, backup_file)
print("Backup with metadata created successfully.")
Explanation:
- Import the
shutil
module. - Define
source_file
as the file to be backed up. - Specify
backup_file
as the new file that will store the backup. - Use
shutil.copy2(source_file, backup_file)
to copy the file along with its metadata. - Print a success message indicating the backup was created.
Output:
Backup with metadata created successfully.
3. Backup a File with a Timestamp in the Filename
In this example, we create a backup copy of a file and append a timestamp to the filename to prevent overwriting previous backups.
main.py
import shutil
import datetime
# Source file path
source_file = "database.db"
# Generate timestamp
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Destination file path with timestamp
backup_file = f"backup_database_{timestamp}.db"
# Copying the file
shutil.copy(source_file, backup_file)
print(f"Backup created: {backup_file}")
Explanation:
- Import
shutil
for copying files anddatetime
for generating timestamps. - Set
source_file
to the original file. - Generate a timestamp using
datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
. - Use
f-string
formatting to create a new filename with the timestamp. - Copy the file using
shutil.copy()
and print the new backup filename.
Output:
Backup created: backup_database_20250213_121530.db
4. Backup a File to a Different Directory
We can specify a different directory for storing the backup file instead of the current working directory.
main.py
import shutil
import os
# Source file path
source_file = "notes.txt"
# Backup directory
backup_dir = "backup_folder"
# Ensure the backup directory exists
os.makedirs(backup_dir, exist_ok=True)
# Destination file path
backup_file = os.path.join(backup_dir, "notes_backup.txt")
# Copy the file
shutil.copy(source_file, backup_file)
print(f"Backup created at: {backup_file}")
Explanation:
- Import
shutil
for file operations andos
to handle directories. - Define
source_file
as the file to back up. - Specify
backup_dir
as the directory where backups will be stored. - Use
os.makedirs(backup_dir, exist_ok=True)
to create the backup directory if it doesn’t exist. - Define
backup_file
as the new file path inside the backup directory. - Copy the file using
shutil.copy()
and print the backup location.
Output:
Backup created at: backup_folder/notes_backup.txt
Conclusion
We explored different methods to create a backup copy of a file using Python. The most common approaches include:
- Using
shutil.copy()
for simple file copies. - Using
shutil.copy2()
to preserve metadata. - Appending a timestamp to avoid overwriting previous backups.
- Saving backup files in a different directory.