fsfwgen/fsfwgen/utility/file_management.py

46 lines
1.4 KiB
Python
Raw Permalink Normal View History

2021-06-08 12:37:10 +02:00
# -*- coding: utf-8 -*-
import logging
2021-06-08 12:37:10 +02:00
import shutil
import os
2022-06-20 18:02:46 +02:00
from pathlib import Path
_LOGGER = logging.getLogger(__name__)
2021-06-08 12:37:10 +02:00
def copy_file(
filename: Path, destination: Path = "", delete_existing_file: bool = False
):
2021-07-31 20:49:38 +02:00
if not os.path.exists(filename):
_LOGGER.warning(f"File {filename} does not exist")
2021-07-31 20:49:38 +02:00
return
2022-03-04 10:24:08 +01:00
if not os.path.isdir(destination) and os.path.exists(destination):
if delete_existing_file:
os.remove(destination)
else:
_LOGGER.warning(f"Destination file {destination} already exists")
2022-03-04 10:24:08 +01:00
return
2021-07-31 20:49:38 +02:00
try:
2022-03-04 10:24:08 +01:00
shutil.copy2(src=filename, dst=destination)
2021-07-31 20:49:38 +02:00
except FileNotFoundError:
_LOGGER.exception("File not found!")
2021-07-31 20:49:38 +02:00
except shutil.SameFileError:
_LOGGER.exception("Source and destination are the same!")
2021-06-08 12:37:10 +02:00
2022-06-20 18:02:46 +02:00
def move_file(file_name: Path, destination: Path = ""):
2021-07-31 20:07:41 +02:00
if not os.path.exists(file_name):
print(f"move_file: File {file_name} does not exist")
2021-07-31 20:07:41 +02:00
return
if not os.path.exists(destination):
print(f"move_file: Destination directory {destination} does not exist")
2021-07-31 20:07:41 +02:00
return
try:
shutil.copy2(file_name, destination)
os.remove(file_name)
return
2021-07-31 20:49:38 +02:00
except FileNotFoundError:
_LOGGER.exception("File not found!")
2021-07-31 20:49:38 +02:00
except shutil.SameFileError:
_LOGGER.exception("Source and destination are the same!")