Skip to content

Instantly share code, notes, and snippets.

@dmwyatt
Last active October 25, 2023 22:09
Show Gist options
  • Save dmwyatt/8087690 to your computer and use it in GitHub Desktop.
Save dmwyatt/8087690 to your computer and use it in GitHub Desktop.
[temporarily replace file] Sometimes when testing I want to replace a file with a test file. This context manager does that. #testing
import contextlib
import shutil
from pathlib import Path
@contextlib.contextmanager
def replace_file(orig, replace_with):
if not replace_with.is_file():
raise ValueError("{} does not exist.".format(replace_with))
if orig.is_file():
# Move orig to backup location
backup_to = backup_fn(orig)
_orig = str(orig)
orig.rename(backup_to)
backed_up_orig = Path(backup_to)
# Replace orig with replacement
shutil.copy(str(replace_with), str(orig))
yield
# Restore original
backed_up_orig.rename(orig)
else:
# No original, just just copy replacement
shutil.copy(str(replace_with), str(orig))
yield
# Remove replacment since there was no original file
orig.unlink(orig)
def backup_fn(path, backup_ext=".bak"):
# Try just slapping the backup_ext on the file
potential = Path(str(path) + backup_ext)
if not potential.exists():
return potential
# Backup already exists so try adding an incremental interger to the fn
for i in range(100):
potential = Path(str(path) + backup_ext + str(i))
if not potential.exists():
return potential
raise ValueError("Unable to choose a filename to back up {} to!".format(path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment