import logging
import traceback
import argparse
logging.basicConfig(level=logging.ERROR)
def safe_file_operation(filepath, operation, *args, **kwargs):
"""
Safely performs an operation on a file, wrapping errors and providing basic validation.
"""
if not isinstance(filepath, str):
raise TypeError("Filepath must be a string.")
try:
# Basic file existence check
with open(filepath, 'r'): # Attempt to open to check if it exists
pass # File exists, proceed
except FileNotFoundError:
raise FileNotFoundError(f"File not found: {filepath}")
except Exception as e: #Catch other file access errors
raise IOError(f"Error accessing file {filepath}: {e}")
try:
operation(filepath, *args, **kwargs)
except Exception as e:
logging.error(f"Error during operation on file {filepath}: {e}")
print(f"An error occurred while processing {filepath}. See logs for details.")
traceback.print_exc() #Print full traceback
raise # Re-raise the exception to stop script execution if needed
def main():
parser = argparse.ArgumentParser(description="Safely perform file operations.")
parser.add_argument("filepath", help="Path to the file.")
parser.add_argument("operation", choices=['read', 'write', 'append'], help="Operation to perform.")
parser.add_argument("-n", "--name", help="Name to write to file (for write/append).")
args = parser.parse_args()
if args.operation == 'read':
safe_file_operation(args.filepath, open, mode='r')
elif args.operation == 'write':
if not args.name:
parser.error("Name argument is required for write operation.")
safe_file_operation(args.filepath, open, mode='w', write=args.name)
elif args.operation == 'append':
if not args.name:
parser.error("Name argument is required for append operation.")
safe_file_operation(args.filepath, open, mode='a', write=args.name)
if __name__ == "__main__":
main()
Add your comment