Loading src/common/file_operations.py 0 → 100644 +142 −0 Original line number Diff line number Diff line #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Provide common utilities for various file operations.""" import json from pathlib import Path # So, here are the tasks for file operations # Use Pathlib package # Create/Delete directory/folder # Tree command/function to walk a directory # Read/Append/Delete file -- default format text # for Json files - use json module # append a key/dict/etc to the JSON would be nice def path_exists(dirc_or_file): """ # function to check if directory/file exists # @params : directory/file to check # @returns : boolean """ return Path(dirc_or_file).exists() def create_directory(dirc=None): """ # function to create directories at the specified path # @params : directory to create # @returns : boolean / None """ if dirc != None: try: if path_exists(dirc): return f"{dirc} already exists." else: Path(dirc).mkdir() return True except FileNotFoundError as e: print(f"Error: {e}") return None def delete_directory(dirc=None): """ # function to delete directories at the specified path # @params : directory to delete # @returns : str / None """ if dirc != None: try: if path_exists(dirc): Path(dirc).rmdir() return f"{dirc} deleted successfully." else: return f"{dirc} does not exist." except FileNotFoundError as e: print(f"Error: {e}") return None def tree(dirc=None): """ # function to walk a directory # @params : directory to walk # @returns : None """ if dirc != None: try: if path_exists(dirc): for item in Path(dirc).glob("*"): if item.is_file(): print(f"File: {item}") elif item.is_dir(): print(f"Directory: {item}") else: return f"{dirc} does not exist." except Exception as e: print(f"Error: {e}") return None def read_file(file_name): """ # function to read a file # @params : file name # @returns : str """ try: with open(f"{file_name}", "r+") as file: if Path(file_name).suffix == ".json": file_contents = json.load(file) else: file_contents = file.read() return file_contents except FileNotFoundError as e: print(f"File doesn't exist: {e}") except json.JSONDecodeError as e: print(f"Invalid JSON file: {e}") return None def append_file(file_name, file_data): """ # function to append contents to a file # @params : file name, data to append # @returns : str / None # append_file function will not work for JSON files as key/value pairs are unordered. """ try: with open(f"{file_name}", "a+") as file: file_contents = file.write(file_data) return f"Contents successfully appended to the file" except FileNotFoundError as e: print(f"File doesn't exist: {e}") except TypeError as te: print(f"Error: {te}, please provide data as string") return None def write_file(file_name, file_data=""): """ # function to write to a file # @params : file name, data to write # @returns : None """ try: if Path(file_name).suffix == ".json": with open(f"{file_name}", "r+") as file: file_contents = json.load(file) file_contents.update(file_data) file.seek(0) json.dump(file_contents, file, indent = 1) else: with open(file_name, "w") as file: file.write(file_data) except FileNotFoundError as e: print(f"File doesn't exist: {e}") except TypeError as te: print(f"Error: {te}, please provide data as string") return None def delete_file(file_name): """ # function to delete a file # @params : file name # @returns : str """ if Path(file_name).exists(): Path(file_name).unlink() return f"File: {file_name} deleted successfully." return f"Error in deleting the file: {file_name}." Loading
src/common/file_operations.py 0 → 100644 +142 −0 Original line number Diff line number Diff line #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Provide common utilities for various file operations.""" import json from pathlib import Path # So, here are the tasks for file operations # Use Pathlib package # Create/Delete directory/folder # Tree command/function to walk a directory # Read/Append/Delete file -- default format text # for Json files - use json module # append a key/dict/etc to the JSON would be nice def path_exists(dirc_or_file): """ # function to check if directory/file exists # @params : directory/file to check # @returns : boolean """ return Path(dirc_or_file).exists() def create_directory(dirc=None): """ # function to create directories at the specified path # @params : directory to create # @returns : boolean / None """ if dirc != None: try: if path_exists(dirc): return f"{dirc} already exists." else: Path(dirc).mkdir() return True except FileNotFoundError as e: print(f"Error: {e}") return None def delete_directory(dirc=None): """ # function to delete directories at the specified path # @params : directory to delete # @returns : str / None """ if dirc != None: try: if path_exists(dirc): Path(dirc).rmdir() return f"{dirc} deleted successfully." else: return f"{dirc} does not exist." except FileNotFoundError as e: print(f"Error: {e}") return None def tree(dirc=None): """ # function to walk a directory # @params : directory to walk # @returns : None """ if dirc != None: try: if path_exists(dirc): for item in Path(dirc).glob("*"): if item.is_file(): print(f"File: {item}") elif item.is_dir(): print(f"Directory: {item}") else: return f"{dirc} does not exist." except Exception as e: print(f"Error: {e}") return None def read_file(file_name): """ # function to read a file # @params : file name # @returns : str """ try: with open(f"{file_name}", "r+") as file: if Path(file_name).suffix == ".json": file_contents = json.load(file) else: file_contents = file.read() return file_contents except FileNotFoundError as e: print(f"File doesn't exist: {e}") except json.JSONDecodeError as e: print(f"Invalid JSON file: {e}") return None def append_file(file_name, file_data): """ # function to append contents to a file # @params : file name, data to append # @returns : str / None # append_file function will not work for JSON files as key/value pairs are unordered. """ try: with open(f"{file_name}", "a+") as file: file_contents = file.write(file_data) return f"Contents successfully appended to the file" except FileNotFoundError as e: print(f"File doesn't exist: {e}") except TypeError as te: print(f"Error: {te}, please provide data as string") return None def write_file(file_name, file_data=""): """ # function to write to a file # @params : file name, data to write # @returns : None """ try: if Path(file_name).suffix == ".json": with open(f"{file_name}", "r+") as file: file_contents = json.load(file) file_contents.update(file_data) file.seek(0) json.dump(file_contents, file, indent = 1) else: with open(file_name, "w") as file: file.write(file_data) except FileNotFoundError as e: print(f"File doesn't exist: {e}") except TypeError as te: print(f"Error: {te}, please provide data as string") return None def delete_file(file_name): """ # function to delete a file # @params : file name # @returns : str """ if Path(file_name).exists(): Path(file_name).unlink() return f"File: {file_name} deleted successfully." return f"Error in deleting the file: {file_name}."