diff --git a/.gitignore b/.gitignore index c12ceb0..f8323ee 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,3 @@ -### FileSystem ignores -tests -app.py -android - # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] diff --git a/README.md b/README.md index 09978dd..4c6eb45 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,16 @@ FileSystem is a powerful toolkit designed to handle file and directory operation ## Getting Started -#### Recommendation +This section will guide you through setting up the environment required to run **FileSystem Pro** effectively. Follow the steps below to ensure a smooth installation and configuration. -It's recommended Python 3.8 or later to use **FileSystem Pro**. You can download the latest version of Python in [python.org](https://www.python.org/). +
+ + Expand to get started + + +#### Requirements + +It's recommended to use Python 3.8 or later to use **FileSystem Pro**. You can download the latest version of Python at [python.org](https://www.python.org/). #### Installation @@ -24,7 +31,7 @@ pip install filesystempro --- -### To Developers / Contributors +### For Developers / Contributors Clone this repository to your local machine using: @@ -47,27 +54,46 @@ Install wheel / Upgrade wheel ```sh pip install --upgrade wheel ``` +
--- +# FileSystem Module + +FileSystem provides a comprehensive suite of methods for managing and interacting with various directories and user folders across multiple operating systems. It intelligently identifies the user's operating system—Linux, macOS, or Windows—and configures file paths for essential directories like Desktop, Documents, Downloads, Music, Pictures, Public, and Videos. Leveraging Python's built-in libraries such as `os`, `sys`, and `getpass`, it ensures cross-platform compatibility and accurate path retrieval. For Windows environments, it uses the `winreg` module to query the Windows registry, ensuring the paths to these directories are accurately retrieved based on the system's registry settings. This makes FileSystem a versatile and reliable tool for any file management needs. + ## Features +FileSystemPro introduces a range of features and enhancements to help you manage and monitor your system's devices more efficiently. + +
+ + Expand to learn about the features + + - **Cross-platform Compatibility:** The code is designed to work on multiple operating systems, including Linux, Mac, and Windows. This makes it versatile and adaptable to different environments. - **Directory Path Identification:** The code identifies and defines the paths to several common user directories based on the operating system. This includes directories like Desktop, Documents, Downloads, Music, Pictures, Public, Videos, and others. -- **Current Working Directory:** The code uses `os.getcwd()` to get the current working directory. - **String Formatting:** The code uses f-string formatting to create directory paths. -- **Monitoring System:** Watcher acts as a monitoring system for the file system. It keeps track of all activities within the file system. -- **Change Tracking:** It records any changes made within the file system. This includes the creation of new files, modification of existing files, and deletion of files. -- **Real-Time Updates:** The Watcher provides real-time updates on any changes made within the file system. This ensures that users have the most current information at all times. +- **Device Module:** Includes powerful tools for managing and retrieving detailed information about your system's disks and CPU, such as disk partitions, CPU usage, and more. +- **Compression Module:** Responsible for creating, extracting, and reading compressed archive files in tar and zip formats. It leverages Python's built-in tarfile and zipfile modules to handle these operations efficiently. +- **Monitoring System (Watcher):** Acts as a monitoring system for the file system. It keeps track of all activities within the file system and provides real-time updates on any changes. +- **Change Tracking:** Records any changes made within the file system. This includes the creation of new files, modification of existing files, and deletion of files. - **Integrity Maintenance:** This feature is particularly useful in scenarios where maintaining the integrity and up-to-date status of the file system is crucial. By tracking all changes, the Watcher helps ensure that the file system remains accurate and reliable. +- **Registry-Based Path Retrieval:** For Windows, the module now uses the `winreg` module to retrieve accurate paths from the Windows registry. It defines paths for the current user's home, Desktop, Documents, Downloads, Music, Pictures, Public, and Videos folders by querying the Windows registry keys. + +
--- -## FileSystem +
+ + Expand to learn about the methods + ```py import filesystem as fs ``` + @@ -88,7 +114,7 @@ import filesystem as fs OS_SEPARATOR @@ -231,11 +257,22 @@ import filesystem as fs
Method - prints the OS separator + Prints the OS separator
'/' for macOS and Linux
'\\' for Windows
-## Sample Codes +The paths for Windows environment are retrieved using the `winreg` module to query the Windows registry for accurate and current folder locations. This ensures that paths such as Desktop, Documents, Downloads, Music, Pictures, Public, and Videos are accurately defined for the user based on the system's registry settings. + +
+ +---
-FileSystem: Reaching Desktop Folder + + Expand for sample codes + +
+ + FileSystem: Reaching the desktop folder + + The following example shows how to get the `Desktop` directory path ```py @@ -258,26 +295,271 @@ Output: ## On Windows C:\Users\YOU\Desktop ``` +
+
+ +--- + +# Compression Module + +The Compression module is responsible for creating, extracting, and reading compressed archive files in tar and zip formats. It leverages Python's built-in tarfile and zipfile modules to handle these operations efficiently. + +## Features + +The Compression Module offers robust and versatile tools for managing file compression and extraction, whether you prefer the tar or zip format. + +
+ + Expand to learn about TarFile + + +### TarFile + +The Tarfile module offers robust and versatile tools for managing file compression and extraction, making it an essential tool for efficient file management. + +
+ +--- + +
+ + Expand to learn about the ZipFile + + +### ZipFile + +The Zipfile module offers robust and versatile tools for managing file compression and extraction, making it an essential tool for efficient file management. + +
+ +--- + +
+ + Expand to learn about the features + + + +- **Create Tar Archive:** This feature allows you to compress a single file, directory, or a list of files and directories into a tar archive. It efficiently bundles multiple files and directories into a single archive file, making it easier to manage and transport. + +- **Extract Tar Archive:** This feature enables you to extract files from a tar archive to a specified destination. You can choose to extract all files or only a specified list of files, providing flexibility in handling the contents of the archive. + +- **Read Tar Archive:** This feature allows you to read and list the contents of a tar archive without extracting them. It provides a convenient way to view the files and directories within the archive before deciding which ones to extract. + +- **Create Zip Archive:** This feature allows you to compress a single file, directory, or a list of files and directories into a zip archive. Similar to the tar archive creation, it bundles multiple files and directories into a single archive file, but in a different format. + +- **Extract Zip Archive:** This feature enables you to extract files from a zip archive to a specified destination. You can choose to extract all files or only a specified list of files, giving you control over which files to retrieve from the archive. + +- **Read Zip Archive:** This feature allows you to read and list the contents of a zip archive without extracting them. It provides a convenient way to inspect the files and directories within the archive before extraction, ensuring you have the information you need. +
--- -# Console +
+ + Expand to learn about the methods + + +The Compression module in FileSystemPro provides a comprehensive set of functions to efficiently manage file compression and extraction, enhancing productivity and versatility in handling various file formats and archives ```py -from filesystem import console as fsconsole +from filesystem import compression +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodDescription
+ compression.tarfile.create_tar(fullpath_files, destination) + + The function compresses files or directories into a TAR file. + Returns a message indicating whether a single file/directory or a list of files/directories was compressed. +
+ compression.tarfile.extract(tar_filename, destination, extraction_list=[]) + + Extract files from a tar archive. It can extract all files or a specified list of files from the archive. + Returns True if the extraction is successful, [FileSystem Pro]: File Not Found if the tar file is not found, False if a specified item in extraction_list is not found and Error Message if any other error occurs during extraction. +
+ compression.tarfile.read_tar_archive(tar_filename) + + Reads the contents of a TAR archive file and returns a list of the names of the files contained within it. +
+ compression.zipfile.create_zip(fullpath_files, destination) + + The function compresses files or directories into a ZIP file. + Returns a message indicating whether a single file/directory or a list of files/directories was compressed. +
+ compression.zipfile.extract(zip_path, destination, extraction_list=None) + + Reads the contents of a ZIP file and extracts files based on the provided parameters. +
+ compression.zipfile.read_zip_archive(zip_filename, show_compression_system_files=True) + + Reads the contents of a ZIP file and returns a list of the names of the files contained within it. +
+
+ +--- + +
+ + Expand for sample codes + + +### ZipFile Sample Codes + +
+Compression: Creating a zip archive + +This code demonstrates how to use the `create_zip` function to create a ZIP archive using **Compression** + +```py +from filesystem import compression +compression.zipfile.create_zip('/path/to/file_or_directory', '/path/to/destination.zip') +``` + +
+ +--- + +
+Compression: Extracting from a zip archive + +This code demonstrates how to use the `extract` function to extract files from a ZIP archive using **Compression**. + +```py +from filesystem import compression +compression.zipfile.extract('/path/to/archive.zip', '/path/to/destination') +``` + +
+ +--- + +
+Compression: Reading a zip archive + +This code demonstrates how to use the read_zip_archive function to read the contents of a ZIP archive using **Compression**. + +```py +from filesystem import compression +contents = compression.zipfile.read_zip_archive('/path/to/archive.zip') +print(contents) +``` + +
+ +--- +### TarFile Sample Codes + +
+Compression: Creating a tar archive + +This code demonstrates how to use the create_tar function to create a TAR archive using **Compression**. + +```py +from filesystem import compression +compression.tar.create_tar('/path/to/file_or_directory', '/path/to/destination.tar') ``` -Console is a robust library designed to enable ANSI escape character sequences, which are used for generating colored terminal text and cursor positioning. -This library is a key addition to FileSystemPro as a third-party library, enhancing the toolkit for developers who require consistent terminal styling across different operating systems. +
+ +--- + +
+Compression: Extracting from a tar archive + +This code demonstrates how to use the extract function to extract files from a TAR archive using **Compression**. + +```py +from filesystem import compression +compression.tar.extract('/path/to/archive.tar', '/path/to/destination') + +``` + +
+ +--- + +
+Compression: Reading a tar archive + +This code demonstrates how to use the read_tar_archive function to read the contents of a TAR archive using **Compression**. + +```py +from filesystem import compression +contents = compression.tar.read_tar_archive('/path/to/archive.tar') +print(contents) +``` + +
+
+ +--- + +# Console Module + +Console is a robust library designed to enable ANSI escape character sequences, which are used for generating colored terminal text and cursor positioning. This library is a key addition to FileSystemPro as a third-party library, enhancing the toolkit for developers who require consistent terminal styling across different operating systems. + ## Features +Unlock the full potential of your Terminal with Console, a robust and feature-rich module that revolutionizes text styling and formatting. + +
+ + Expand to learn about the features + + - **Universal Compatibility:** Console ensures that applications or libraries utilizing ANSI sequences for colored output on Unix or Macs can now operate identically on Windows systems. - **Simplified Integration:** With no dependencies other than the standard library, integrating Console into your projects is straightforward. It’s tested across multiple Python versions, ensuring reliability. - **Enhanced Terminal Experience:** By converting ANSI sequences into appropriate win32 calls, Console allows Windows terminals to emulate the behavior of Unix terminals, providing a consistent user experience. - **Effortless Transition:** For developers transitioning to FileSystemPro, incorporating Console into your workflow is effortless, enabling you to maintain the visual aspects of your terminal applications without platform constraints. +
+ +--- + +
+ + Expand to learn about the methods + + +These constants are used to control the appearance of text output in the terminal, including foreground and background colors, as well as text styles. By utilizing these constants, developers can enhance the readability and visual appeal of their terminal applications, ensuring a consistent experience across different operating systems. + +```py +from filesystem import console as fsconsole +``` + @@ -306,9 +588,15 @@ This library is a key addition to FileSystemPro as a third-party library, enhanc
Constants
+
-## Sample Codes +--- +
+ + Expand for sample codes + + > [!NOTE] > Please note that **GitHub (and PYPI) does not support colored text** in README files. This is due to the limitations of the markdown language used in GitHub (and PYPI) READMEs, which does not have built-in support for text color changes. @@ -342,6 +630,7 @@ This is a new warn message
+---
Console: Printing a blue background text message @@ -373,6 +662,8 @@ This is a new blue background message
+--- +
Console: Different foregrounds, backgrounds and styles @@ -399,21 +690,192 @@ Output:
+--- + Remember, for the color changes to work, your Terminal must support ANSI escape sequences, which are used to set the color. Not all Terminals do, so if you’re not seeing the colors as expected, that could be why. + + + +--- + +# Device Module + +The Device module includes powerful tools for managing and retrieving detailed information about your system's disks and CPU. + +## Features + +The Device module includes powerful tools for managing and retrieving detailed information about your system's disks and CPU, enhancing productivity and ensuring efficient system management in applications. + +
+ + Expand to learn about Disks + + +### Disks + +The Disks section of the Device module provides powerful tools for managing and retrieving detailed information about disk partitions, boot drive names, filesystem types, and storage metrics. It enhances productivity by simplifying disk management and ensuring efficient retrieval of disk-related information. +
+ +--- + +
+ + Expand to learn about the CPU + + +### CPU + +The CPU section of the Device module offers essential metrics and functionalities for monitoring CPU performance, including CPU usage percentage, CPU times, and the number of CPU cores. It empowers developers to efficiently manage and optimize CPU usage within their applications. + +
+ +--- + +
+ + Expand to learn about the features + + + +- **Boot Time:** Provides the system's boot time. +- **Current Disk Filesystem Name:** Returns the name of the current disk filesystem. +- **Disk Info:** Displays detailed information about the disks. +- **Disk I/O Counters:** Returns disk I/O counters. +- **Disk Partitions:** Retrieves disk partitions. +- **Boot Drive Name:** Returns the name of the boot drive. +- **Filter by Device:** Filters disk partitions based on the device. +- **Filter by Filesystem Type:** Filters disk partitions based on filesystem type. +- **Filter by Mount Point:** Filters disk partitions based on the mount point. +- **Filter by Options:** Filters disk partitions based on options. +- **Storage Metrics:** Provides storage metrics for a specific mount point. +- **CPU Usage Percentage:** Returns the CPU usage percentage. +- **CPU Usage Times:** Provides CPU usage times. +- **CPU Count:** Returns the number of CPUs (logical cores) available in the system. + +
+ +--- + +
+ + Expand to learn about the methods + + +The Directory module in FileSystemPro brings a comprehensive set of methods that streamline and enhance directory management + +```py +from filesystem import device +``` + + + + + + + + + + + + +
MethodDescription
+ directory.combine(*args, paths=[]) + + Combines a list of paths or arguments into a single path. If the first argument or the first element in the paths list is not an absolute path, it raises a ValueError. +
+
--- -# Directory +
+ + Expand for sample codes + + +
+Directory: Check if exists + +The following example check whether a directory exists within the file system and print the result using **Directory** + +```py +import filesystem as fs +from filesystem import directory as dir + +documents_exists = dir.exists(fs.documents) + +print(documents_exists) +``` + +Output: + +``` +True +``` +
+ +
+Directory: Listing directories inside a folder + +The following example shows how to lists all directories in the specified path using **Directory** ```py +import filesystem as fs from filesystem import directory as dir + +folder_list = dir.get_directories(fs.documents) + +print(folder_list) ``` +Output: + +``` +['Work', 'School', 'PicsBackups', 'Office Documents'] +``` +
+ +
+Directory: Renaming a folder + +The following example shows how rename a folder using **Directory** + +```py +import filesystem as fs +from filesystem import directory as dir + +new_name = dir.rename(f'{fs.documents}/MyFolder', f'{fs.documents}/NewFolder') + +print(new_name) +``` + +Output: + +``` +True +``` +
+ +--- + +
+ +--- + +# Directory Module + The Directory module is a component of the FileSystemPro library that provides a collection of functions for handling directory-related operations. It simplifies tasks such as path manipulation, directory creation and deletion, and file retrieval within directories. ## Features + +The Directory module simplifies directory-related tasks like path manipulation, directory creation and deletion, and file retrieval. It enhances productivity and ensures efficient directory management in applications. + +
+ + Expand to learn about the features + + - **Path Combination:** Dynamically combines multiple paths into a single path string. - **Directory Creation:** Creates new directories, with an option to create necessary subdirectories. - **Directory Deletion:** Deletes directories, with an option for recursive deletion. @@ -423,83 +885,151 @@ directory creation and deletion, and file retrieval within directories. - **Directory Listing:** Lists all subdirectories within a given directory. - **Directory Renaming:** Renames a directory if it exists. +
+ +--- + +
+ + Expand to learn about the methods + + +The Directory module in FileSystemPro brings a comprehensive set of methods that streamline and enhance directory management + +```py +from filesystem import directory as dir +``` + - - + + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + - - + - - - + directory.get_size(directory_path) + + Calculates the total size of all files in the specified directory. The size is returned in bytes, KB, MB, GB, or TB, depending on the total size. + + - - - - + directory.join(path1='', path2='', path3='', path4='', paths=[]) + + Joins multiple directory paths into a single path. The function ensures that each directory path ends with a separator before joining. If a directory path does not end with a separator, one is added. + + - - - - + directory.move(source, destination, move_root=True) + - + The move function is designed to move files or directories from a source location to a destination. + It provides flexibility by allowing you to specify whether intermediate-level subdirectories should be created during the move operation. + + + + - - - - + directory.rename(old_path, new_path) + + Renames a directory from the old directory path to the new directory path. If the old directory path does not exist or is not a directory, the function returns False. +
MethodDescriptionMethodDescription
directory.combine(*args, paths=[]) + directory.combine(*args, paths=[]) + Combines a list of paths or arguments into a single path. If the first argument or the first element in the paths list is not an absolute path, it raises a ValueError.
+ directory.create(path, create_subdirs = True) + + Creates a directory at the specified path. If `create_subdirs` is True, all intermediate-level + directories needed to contain the leaf directory will be created. After the directory is created, + it returns the details of the created directory. +
+ directory.delete(path, recursive=False) + + Deletes a directory at the specified path. If `recursive` is True, the directory and all its contents will be removed. +
+ directory.exists(path) + + Checks if a directory exists at the specified path. +
+ directory.get_directories(path, fullpath=True) + + Create a list of directories within a specified path and returns either their full paths or just their names based on the fullpath parameter. Defaults to True. +
+ directory.get_name(path) + + Retrieves the name of the directory of the specified path. + If the path has an extension, it is assumed to be a file, and the parent directory name is returned. + If the path does not have an extension, it is assumed to be a directory, + and the directory name is returned. +
directory.create(path, create_subdirs = True) - Creates a directory at the specified path. If `create_subdirs` is True, all intermediate-level - directories needed to contain the leaf directory will be created. After the directory is created, - it returns the details of the created directory. + directory.get_parent(path) + + Retrieves the parent directory from the specified path. +
+ directory.get_parent_name(path) + + Retrieves the parent directory name from the specified path.
directory.delete(path, recursive=False)
- Deletes a directory at the specified path. If `recursive` is True, the directory and all its contents will be removed. -
directory.exists(path) - Checks if a directory exists at the specified path. -
directory.get_directories(path, fullpath=False) - Retrieves a list of directories within the specified path. -
directory.get_name(path) - Retrieves the name of the directory of the specified path. - If the path has an extension, it is assumed to be a file, and the parent directory name is returned. - If the path does not have an extension, it is assumed to be a directory, - and the directory name is returned. -
directory.get_parent_name(path) - Retrieves the parent directory name from the specified path. -
directory.get_parent(path) - Retrieves the parent directory from the specified path. -
directory.join(path1='', path2='', path3='', path4='', paths=[]) - Joins multiple directory paths into a single path. The function ensures that each directory path ends with a separator before joining. If a directory path does not end with a separator, one is added. -
directory.rename(old_path, new_path) - Renames a directory from the old directory path to the new directory path. If the old directory path does not exist or is not a directory, the function returns False. -
+
-## Sample Codes +--- +
+ + Expand for sample codes + +
Directory: Check if exists @@ -565,17 +1095,26 @@ True --- -# File +
-```py -from filesystem import file as fsfile -``` +--- + +# File Module The File module is a comprehensive utility toolset that forms part of the FileSystemPro library. It provides a suite of functions designed to handle various file operations such as integrity checks, file creation, deletion, enumeration, and file splitting and reassembling. + ## Features + +The File module is packed with a variety of features aimed at simplifying and optimizing file management tasks. From calculating file integrity to creating, deleting, and managing files, these features are designed to provide robust solutions for handling all your file-related operations. + +
+ + Expand to learn about the features + + - **Checksum Calculation:** Utilizes SHA-256 hashing to calculate file checksums for integrity verification. - **Integrity Check:** Compares checksums of two files to verify their integrity. - **File Creation:** Supports creating both text and binary files with specified data. @@ -587,6 +1126,21 @@ file creation, deletion, enumeration, and file splitting and reassembling. - **File Reassembling:** Reassembles split files back into a single file. - **File Splitting:** Splits a file into smaller parts based on a specified chunk size. +
+ +--- + +
+ + Expand to learn about the methods + + +The Directory module in FileSystemPro brings a comprehensive set of methods that streamline and enhance directory management + +```py +from filesystem import file as fsfile +``` + @@ -615,10 +1169,9 @@ file creation, deletion, enumeration, and file splitting and reassembling. - + @@ -652,6 +1205,14 @@ file creation, deletion, enumeration, and file splitting and reassembling. + + + + + - + + + + + + - -
Method
file.create(file, data, encoding="utf-8")file.create(file, data, overwrite=False, encoding="utf-8") - Creates a file at the specified path and writes data into it. If the file already exists, - its contents are overwritten. The function then returns the details of the created file. + Creates a file at the specified path and writes data into it. If the file already exists, its contents can be either appended to or overwritten based on the overwrite parameter. The function then returns the details of the created file
file.find_duplicates(path) + Finds duplicate files in a given directory and its subdirectories. + A file is considered a duplicate if it has the same checksum as another file. +
file.get_extension(file_path, lower=True) @@ -660,12 +1221,20 @@ file creation, deletion, enumeration, and file splitting and reassembling.
file.get_files(path, fullpath=False, extension=None)file.get_files(path, fullpath=True, extension=None) Retrieves a list of files from the specified directory. Optionally, it can return the full path of each file and filter files by their extension.
file.get_size(file_path) + Calculates the size of a file at the specified path. + The size is returned in bytes, KB, MB, GB, or TB, depending on the size. +
file.move(source, destination, new_filename=None, replace_existing=False) @@ -697,12 +1266,16 @@ file creation, deletion, enumeration, and file splitting and reassembling. Splits a large file into smaller chunks. The function reads the file in chunks of a specified size and writes each chunk to a new file. The new files are named by appending `.fsp` and an index number to the original filename.
+
-## Sample Codes +--- +
+ + Expand for sample codes + +
File: Check Integrity @@ -761,112 +1334,49 @@ None output --- -# Wrapper +
-```py -from filesystem import wrapper as wra -``` +--- + +# Wrapper Module Wrapper is a comprehensive toolkit that provides a set of utility functions specifically designed to facilitate file and directory operations. These operations may include creating, reading, updating, and deleting files or directories. - - - - - - - - - - - +## Features +Wrapper is an integral part of the FileSystemPro library, designed to provide detailed information about +files and directories. +It includes functions for retrieving metadata and checking file extensions. - - - - - +
+ + Expand to learn about the features + + +- **Metadata Retrieval:** Gathers comprehensive metadata about a file or directory path. +- **Extension Check:** Determines whether a file has an extension. -
- - - - + - - - - - - - - - - - +--- - - - - - +
+ + Expand to learn about the methods + + +The Wrapper module in FileSystemPro brings a comprehensive set of methods that streamline and enhance file and directory management. + +```py +from filesystem import wrapper as wra +``` +
MethodDescriptionStatus
wrapper.combine(*args, paths=[]) - This function is designed to combine file or directory paths. It takes any number of arguments *args and an optional parameter paths which is a list of paths. The function returns a combined path based on the inputs. - If the paths list is provided, the function uses it to combine paths. It starts with the first path in the list and checks if it’s an absolute path. If it’s not, it raises a ValueError with a detailed error message. Then, it iterates over the rest of the paths in the list. If a path is absolute, it replaces the current result with this path. If a path is relative, it joins this path to the current result. Finally, it returns the combined path. - If the paths list is not provided or is empty, the function uses the arguments passed *args. It starts with the first argument and checks if it’s an absolute path. If it’s not, it raises a ValueError with a detailed error message. Then, it iterates over the rest of the arguments. If an argument is an absolute path, it replaces the current result with this path. If an argument is a relative path and not an empty string, it adds this path to the current result. If the current result doesn’t end with a separator (os.sep), it adds one before adding the path. Finally, it returns the combined path. -

Please note: This function does not check if the paths exist or are valid, it only combines them based on the rules described. It’s up to the caller to ensure that the paths are valid and exist if necessary. -

This method is intended to concatenate individual strings into a single string that represents a file path. However, if an argument other than the first contains a rooted path, any previous path components are ignored, and the returned string begins with that rooted path component. As an alternative to the combine method, consider using the join method. -
- Under support. Consider using directory.combine(*args, paths=[]) -
- wrapper.create_directory(path, create_subdirs=True) - - This function is used to create a directory at the specified path. If create_subdirs is True, the function creates all intermediate-level directories needed to contain the leaf directory. If create_subdirs is False, the function will raise an error if the directory already exists or if any intermediate-level directories in the path do not exist. -
Default is True -
If the directories already exist, it does nothing. -
- Under support. Consider using directory.create(path, create_subdirs = True) -
- wrapper.create_file(file_name, path, text, encoding="utf-8-sig") - - The function attempts to open a file at the specified path with the given file_name (with extension), in write mode with the specified encoding. It then writes the provided text into the file. -
Finally, it calls Wrapper get_object with the full path to the newly created file and returns the resulting dictionary. -
- Under support. Consider using file.create(file, data, encoding="utf-8-sig") -
- wrapper.delete(path, recursive=False) - - This function is designed to delete a directory at a given path. - If recursive is set to True, the function will delete the directory and all its contents. If it’s False, the function will only delete the directory if it’s empty. Default is False. - - Under support. Consider using directory.delete(path, recursive=False) -
- wrapper.find_duplicates(path) - - Finds duplicate files in a given directory and its subdirectories. A file is considered a duplicate if it has the same checksum as another file. - - Supported -
- wrapper.enumerate_files(path) - - This function performs a depth-first traversal of the directory tree at the given path (after expanding any user home directory symbols). It returns a list of dictionaries containing the attributes of each file and directory in the tree. - - Under support. Consider using file.enumerate_files(path) -
- - - + + - - - - - - - - @@ -900,102 +1393,20 @@ Wrapper is a comprehensive toolkit that provides a set of utility functions spec - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
- wrapper.get_files(path) - - This function takes a path as input (which can include wildcards), expands any user home directory symbols (~), and returns a list of dictionaries containing the attributes of each file or directory that matches the path. - - Under support. Consider using file.get_files(path) - MethodDescription
wrapper.get_object(path) @@ -874,23 +1384,6 @@ Wrapper is a comprehensive toolkit that provides a set of utility functions spec This function takes a file or directory path as input and returns a dictionary containing various attributes of the file or directory. These attributes include the time of last modification, creation time, last access time, name, size, absolute path, parent directory, whether it's a directory or file or link, whether it exists, and its extension (if it's a file). - Supported -
- wrapper.get_size(file_path) - - Calculates the size of the file or directory at the specified path. If the path is a directory, - it calculates the total size of all files in the directory. The size is returned in bytes, KB, - MB, GB, or TB, depending on the size. - - Supported -
Checks if the given file path has an extension. This function can return True or False based on the string, even if the file or directory does not exist. - Supported -
- wrapper.join(path1='', path2='', path3='', path4='', paths=[]) - - This function is designed to concatenate directory paths. It takes four optional string parameters path1, path2, path3, path4 and an optional list of paths paths. The function returns a single string that represents the concatenated path. -
For each of the parameters path1, path2, path3 and path4, the function checks if the path ends with a separator. If it doesn’t, and the path is not an empty string, it adds a separator to the end of the path. - If the paths list is provided and is not empty, the function iterates over each item in the list. For each item, it checks if the item ends with a separator. If it doesn’t, it adds a separator to the end of the item. - Finally, the function returns the concatenated path. -

Please note: This function does not check if the paths exist or are valid, it only combines them based on the rules described. It’s up to the caller to ensure that the paths are valid and exist if necessary. -

Unlike the combine method, the join method does not attempt to root the returned path. (That is, if path2 or path3 or path4 is an absolute path, the join method does not discard the previous paths as the combine method does). -
- Under support. Consider using directory.join(path1='', path2='', path3='', path4='', paths=[]) -
- wrapper.list_directories(path) - - This function returns a list of all the directories in a given directory. - - Under support. Consider using directory.get_directories(path) -
- wrapper.list_files(path) - - This function returns a list of all the files in a given directory. - - Under support. Consider using file.get_files(path) -
- wrapper.make_zip(source, destination) - - This function is used to create a zip archive of a given source directory and move it to a specified destination. - - Supported -
- wrapper.read_zip_file_contents(zip_filename) - - Reads the contents of a ZIP file and returns a list of the names of the files contained within it. - - New implementation -
+
-## Sample Codes +---
-Wrapper: Make a zip file - -Creates a zip archive of the specified source directory or file and moves it to the specified destination using **Wrapper** - -- Creates a zip archive of a **directory** and moves it to a destination. - -```python -from filesystem import wrapper as wra - -wra.make_zip("/path/to/directory", "/path/to/directory.zip") -``` - -- Creates a zip archive of a **file** and moves it to a destination. - -```python -from filesystem import wrapper as wra - -wra.make_zip("/path/to/file.txt", "/path/to/file.zip") -``` -
- + + Expand for sample codes + +
Wrapper: Has Extension @@ -1036,37 +1447,49 @@ False This will return **False** because the file does not have an extension.
-
-Wrapper: Get size of file or directory +--- -Calculates the size of the file or directory at the specified path. +
-```py -import filesystem as fs -from filesystem import wrapper as wra +--- -documents_size = wra.get_size(fs.documents) +# Watcher Module -print(documents_size) -``` +Watcher serves as a monitoring system for the file system. It keeps track of any changes made within the file system, such as the creation of new files, modification of existing files, or deletion of files. This feature allows for real-time updates and can be particularly useful in scenarios where maintaining the integrity and up-to-date status of the file system is crucial. -Output: -```sh -1.6 GB -``` +## Features + +Watcher could be useful in scenarios where you need to monitor changes to a file system, for example, in a backup system or a live syncing service. + +
+ + Expand to learn about the features + + +- **Initialization:** The constructor method init(self, root) initializes the Watcher object with a root directory to watch and saves the current state of the file system. + +- **State Retrieval:** The get_state(self, path) method returns a dictionary of all files in the given path with their metadata. + +- **Change Detection:** The diff(self) method compares the current state of the file system with the saved state to identify any changes (created, updated, or removed files) and returns a list of dictionaries with the metadata of changed files and the type of change. + +- **String Representation:** The str(self) method returns a string representation of the Watcher object. +
--- -# Watcher +
+ + Expand to learn about the methods + + +The Wrapper module in FileSystemPro brings a comprehensive set of methods that streamline and enhance file and directory management. ```py from filesystem import watcher as wat ``` -Watcher serves as a monitoring system for the file system. It keeps track of any changes made within the file system, such as the creation of new files, modification of existing files, or deletion of files. This feature allows for real-time updates and can be particularly useful in scenarios where maintaining the integrity and up-to-date status of the file system is crucial. - @@ -1102,11 +1525,15 @@ Watcher serves as a monitoring system for the file system. It keeps track of any
Method
+
-This class could be useful in scenarios where you need to monitor changes to a file system, for example, in a backup system or a live syncing service. - -## Sample Codes +--- +
+ + Expand for sample codes + +
Watcher: Monitoring Documents Folder @@ -1138,4 +1565,8 @@ while True: --- +
+ +--- + Copyright © 2023–2024 Bisneto Inc. All rights reserved. \ No newline at end of file diff --git a/filesystem/__core__/__init__.py b/filesystem/__core__/__init__.py index 9a3db38..4830e72 100644 --- a/filesystem/__core__/__init__.py +++ b/filesystem/__core__/__init__.py @@ -52,7 +52,7 @@ import requests from filesystem import console as fsconsole -__version__ = "1.0.4.0" +__version__ = "2.0.0.0" def __checkupdates__(user, repo): """ diff --git a/filesystem/__init__.py b/filesystem/__init__.py index d448450..82d221d 100644 --- a/filesystem/__init__.py +++ b/filesystem/__init__.py @@ -129,27 +129,33 @@ """ elif PLATFORM == "win32" or PLATFORM == "win64": PLATFORM_NAME = "Windows" + import winreg + def get_registry_paths(folder_name): + sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key: + return winreg.QueryValueEx(key, folder_name)[0] + user = os.environ['USERPROFILE'] """ Creates a string that represents the path to the current user's home directory. """ - desktop = f'{user}/Desktop' + desktop = get_registry_paths("Desktop") """ Creates a string that represents the path to the current user's Desktop folder. """ - documents = f'{user}/Documents' + documents = get_registry_paths("Personal") """ Creates a string that represents the path to the current user's Documents folder. """ - downloads = f'{user}/Downloads' + downloads = get_registry_paths("{374DE290-123F-4565-9164-39C4925E467B}") """ Creates a string that represents the path to the current user's Downloads folder. """ - music = f'{user}/Music' + music = get_registry_paths("My Music") """ Creates a string that represents the path to the current user's Music folder. """ - pictures = f'{user}/Pictures' + pictures = get_registry_paths("My Pictures") """ Creates a string that represents the path to the current user's Pictures folder. """ @@ -157,7 +163,7 @@ """ Creates a string that represents the path to the current user's Public folder. """ - videos = f'{user}/Videos' + videos = get_registry_paths("My Video") """ Creates a string that represents the path to the current user's Videos folder. """ @@ -176,7 +182,7 @@ - Tip: Use `fs.videos` instead: -``` +```python import filesystem as fs print(fs.videos) ``` diff --git a/filesystem/compression/__init__.py b/filesystem/compression/__init__.py new file mode 100644 index 0000000..f6db351 --- /dev/null +++ b/filesystem/compression/__init__.py @@ -0,0 +1,35 @@ +""" +# Compression + +--- + +## Overview +The Compression module is a module for creating, extracting, and reading compressed archive files +in both tar and zip formats. +It leverages Python's built-in `tarfile` and `zipfile` modules to handle these operations efficiently. + +1. **Creating Archives:** The module provides functions to compress files and directories into tar or zip archives. It supports both single files and directories, as well as lists of files and directories. + +2. **Extracting Archives:** It includes functions to extract files from tar or zip archives. Users can extract all contents or specify a list of files to extract. + +3. **Reading Archives:** The module allows users to read the contents of tar or zip archives, listing all files contained within the archive. + +### Tarfile Module + +- **Functions**: + 1. **`create_tar(fullpath_files, destination)`**: Compresses a single file, directory, or a list of files/directories into a tar archive. + 2. **`extract(tar_filename, destination, extraction_list=[])`**: Extracts files from a tar archive to a specified destination. It can extract all files or a specified list of files. + 3. **`read_tar_archive(tar_filename)`**: Reads and lists the contents of a tar archive. + +### Zipfile Module + +- **Functions**: + 1. **`create_zip(fullpath_files, destination)`**: Compresses a single file, directory, or a list of files/directories into a zip archive. + 2. **`extract(zip_filename, destination, extraction_list=[])`**: Extracts files from a zip archive to a specified destination. It can extract all files or a specified list of files. + 3. **`read_zip_archive(zip_filename)`**: Reads and lists the contents of a zip archive. + +This module is useful for managing compressed files, providing a unified interface for handling both tar and zip formats. It simplifies the process of archiving and extracting files, making it a valuable tool for data compression and archiving tasks. +""" + +from . import tarfile +from . import zipfile \ No newline at end of file diff --git a/filesystem/compression/tarfile.py b/filesystem/compression/tarfile.py new file mode 100644 index 0000000..577df1c --- /dev/null +++ b/filesystem/compression/tarfile.py @@ -0,0 +1,202 @@ +""" +# TarFile + +--- + +## Overview +This module provides functions to create, extract, and read tar archives. It is designed to handle both single files and directories, making it versatile for various file compression and extraction needs. + +## Features +- **Create Tar Archives:** Compress single files or directories into a tar archive. +- **Extract Tar Archives:** Extract all or specific files from a tar archive. +- **Read Tar Archives:** List the contents of a tar archive. + + +## Usage +To use these functions, simply import the module and call the desired function with appropriate parameters: + +```python +import os +import tarfile + +# Example: Creating a tar archive +create_tar('/path/to/file_or_directory', '/path/to/destination.tar') + +# Example: Extracting from a tar archive +extract('/path/to/archive.tar', '/path/to/destination') + +# Example: Reading a tar archive +contents = read_tar_archive('/path/to/archive.tar') +print(contents) +``` +""" + +import os +import tarfile + +def create_tar(fullpath_files, destination): + """ + # compression.create_tar(fullpath_files, destination) + + --- + + ### Overview + The `create_tar` function compresses files or directories into a TAR file. + + ### Parameters: + - **fullpath_files (str or list)**: The path(s) to the file(s) or directory(ies) to be compressed. It can be a single string or a list of strings. + - **destination (str)**: The path where the resulting TAR file will be saved. + + ### Function Details: + 1. **add_to_tar(tarf, path, base_path)**: A helper function that adds files to the TAR archive. + - If `path` is a file, it writes the file to the TAR archive. + - If `path` is a directory, it recursively adds all files in the directory to the TAR archive. + + 2. **Main Function Logic**: + - If `fullpath_files` is a string, it compresses the single file or directory specified by the string. + - If `fullpath_files` is a list, it compresses each file or directory in the list. + + ### Returns: + - A message indicating whether a single file/directory or a list of files/directories was compressed. + + ### Examples: + - Compressing a single file or directory: + ```python + create_tar("/path/to/file_or_directory", "/path/to/destination.tar") + ``` + + - Compressing multiple files or directories: + ```python + create_tar(["/path/to/file1", "/path/to/directory2"], "/path/to/destination.tar") + ``` + """ + def add_to_tar(tarf, path, base_path): + if os.path.isfile(path): + tarf.add(path, os.path.relpath(path, base_path)) + else: + for root, _, files in os.walk(path): + for file in files: + file_path = os.path.join(root, file) + tarf.add(file_path, os.path.relpath(file_path, base_path)) + + if isinstance(fullpath_files, str): + with tarfile.open(destination, 'w') as tarf: + add_to_tar(tarf, fullpath_files, os.path.dirname(fullpath_files)) + return "ONLY ONE FILE OR DIRECTORY WAS COMPRESSED" + + if isinstance(fullpath_files, list): + with tarfile.open(destination, 'w') as tarf: + for item in fullpath_files: + add_to_tar(tarf, item, os.path.dirname(item)) + return "A LIST OF FILE OR DIRECTORY WAS COMPRESSED" + +def extract(tar_filename, destination, extraction_list=[]): + """ + # compression.extract(tar_filename, destination, extraction_list=[]) + + --- + + ### Overview + The `extract` function is designed to extract files from a tar archive. It can extract all files or a specified list of files from the archive. + + ### Parameters: + - **tar_filename (str)**: The path to the tar file that needs to be extracted. + - **destination (str)**: The directory where the extracted files will be saved. + - **extraction_list (list, optional)**: A list of specific files or directories to extract from the tar file. If this list is empty, all files will be extracted. + + ### Function Details: + 1. **Opening the Tar File**: + - The function attempts to open the tar file specified by `tar_filename` in read mode (`"r:*"`). + + 2. **Extracting Files**: + - If `extraction_list` is empty, the function extracts all files to the `destination` directory. + - If `extraction_list` contains specific items, the function checks if each item exists in the tar file: + - If the item exists, it extracts the item to the `destination`. + - If the item does not exist, it checks for any files in the tar archive that start with the item's name and extracts those. + + 3. **Error Handling**: + - If the tar file is not found, the function returns a message indicating the file was not found. + - If a specified item in `extraction_list` is not found, the function returns `False`. + - For any other exceptions, the function returns a message with the error details. + + ### Returns: + - **True**: If the extraction is successful. + - **"[FileSystem Pro]: File Not Found"**: If the tar file is not found. + - **False**: If a specified item in `extraction_list` is not found. + - **Error Message**: If any other error occurs during extraction. + + ### Examples: + - Extracting all files from a tar archive: + ```python + extract("archive.tar.gz", "/path/to/destination") + ``` + + - Extracting specific files from a tar archive: + ```python + extract("archive.tar.gz", "/path/to/destination", ["file1.txt", "dir2/"]) + ``` + """ + try: + with tarfile.open(tar_filename, "r:*") as tar_file: + if len(extraction_list) == 0: + tar_file.extractall(destination) + return True + + for item in extraction_list: + if item in tar_file.getnames(): + tar_file.extract(item, destination) + else: + for i in tar_file.getnames(): + if i.startswith(item): + tar_file.extract(i, destination) + return True + + except FileNotFoundError: + return "[FileSystem Pro]: File Not Found" + except KeyError: + return False + except Exception as e: + return f"[FileSystem Pro]: An error occurred.\nError: {e}" + +def read_tar_archive(tar_filename): + """ + # compression.read_tar_archive(tar_filename) + + --- + + ### Overview + The `read_tar_archive` function reads the contents of a TAR archive file and returns a list of the names of the files contained within it. + + ### Parameters: + - **tar_filename (str)**: The path to the TAR archive file to be read. + + ### Function Details: + 1. **Opening the TAR file**: + - The function attempts to open the specified TAR file in read mode using `tarfile.open(tar_filename, "r")`. + - If the file is successfully opened, it retrieves the names of all the files in the archive using `tar_file.getnames()` and returns this list. + + 2. **Error Handling**: + - If the specified TAR file is not found, the function catches the `FileNotFoundError` and returns the message `"[FileSystem Pro]: File Not Found"`. + - If any other exception occurs, it catches the exception and returns a message indicating an error occurred, along with the error message. + + ### Returns: + - A list of file names contained in the TAR archive if successful. + - A string message indicating an error if the file is not found or another exception occurs. + + ### Examples: + - Reading the contents of a TAR archive: + ```python + tar_contents = read_tar_archive("/path/to/archive.tar") + print(tar_contents) + ``` + + This function is useful for quickly listing the contents of a TAR archive without extracting the files. + """ + try: + with tarfile.open(tar_filename, "r") as tar_file: + tar_contents_list = tar_file.getnames() + return tar_contents_list + except FileNotFoundError: + return "[FileSystem Pro]: File Not Found" + except Exception as e: + return f"[FileSystem Pro]: An error occurred. Error: {e}" diff --git a/filesystem/compression/zipfile.py b/filesystem/compression/zipfile.py new file mode 100644 index 0000000..d319e68 --- /dev/null +++ b/filesystem/compression/zipfile.py @@ -0,0 +1,181 @@ +""" +# ZipFile + +--- + +## Overview +This module provides functions to create, extract, and read zip archives. It is designed to handle both single files and directories, making it versatile for various file compression and extraction needs. + +## Features +- **Create Zip Archives:** Compress single files or directories into a zip archive. +- **Extract Zip Archives:** Extract all or specific files from a zip archive. +- **Read Zip Archives:** List the contents of a zip archive. + +## Usage +To use these functions, simply import the module and call the desired function with appropriate parameters: + +```python +import os +import zipfile + +# Example: Creating a zip archive +create_zip('/path/to/file_or_directory', '/path/to/destination.zip') + +# Example: Extracting from a zip archive +extract('/path/to/archive.zip', '/path/to/destination') + +# Example: Reading a zip archive +contents = read_zip_archive('/path/to/archive.zip') +print(contents) +``` +""" + +import os +import zipfile +from filesystem import wrapper as wra + +def create_zip(fullpath_files, destination): + """ + # compression.zipfile.create_zip(fullpath_files, destination) + + --- + + ### Overview + The `create_zip` function compresses files or directories into a ZIP file. + + ### Parameters: + - **fullpath_files (str or list)**: The path(s) to the file(s) or directory(ies) to be compressed. It can be a single string or a list of strings. + - **destination (str)**: The path where the resulting ZIP file will be saved. + + ### Function Details: + 1. **add_to_zip(zipf, path, base_path)**: A helper function that adds files to the ZIP archive. + - If `path` is a file, it writes the file to the ZIP archive. + - If `path` is a directory, it recursively adds all files in the directory to the ZIP archive. + + 2. **Main Function Logic**: + - If `fullpath_files` is a string, it compresses the single file or directory specified by the string. + - If `fullpath_files` is a list, it compresses each file or directory in the list. + + ### Returns: + - A message indicating whether a single file/directory or a list of files/directories was compressed. + + ### Examples: + - Compressing a single file or directory: + ```python + create_zip("/path/to/file_or_directory", "/path/to/destination.zip") + ``` + + - Compressing multiple files or directories: + ```python + create_zip(["/path/to/file1", "/path/to/directory2"], "/path/to/destination.zip") + ``` + """ + def add_to_zip(zipf, path, base_path): + if os.path.isfile(path): + zipf.write(path, os.path.relpath(path, base_path)) + else: + for root, _, files in os.walk(path): + for file in files: + file_path = os.path.join(root, file) + zipf.write(file_path, os.path.relpath(file_path, base_path)) + + if isinstance(fullpath_files, str): + with zipfile.ZipFile(destination, 'w') as zipf: + add_to_zip(zipf, fullpath_files, os.path.dirname(fullpath_files)) + return "ONLY ONE FILE OR DIRECTORY WAS COMPRESSED" + + if isinstance(fullpath_files, list): + with zipfile.ZipFile(destination, 'w') as zipf: + for item in fullpath_files: + add_to_zip(zipf, item, os.path.dirname(item)) + return "A LIST OF FILE OR DIRECTORY WAS COMPRESSED" + +def extract(zip_path, destination, extraction_list=None): + """ + # compression.zipfile.extract(zip_path, destination, extraction_list=None) + + --- + + ### Overview + Reads the contents of a ZIP file and extracts files based on the provided parameters. + + ### Parameters: + - **zip_filename (str)**: The path to the ZIP file to read. + - **extraction_list (None, list, or str)**: Specifies which files to extract. If `None`, all files are extracted. If a list, only the files in the list are extracted. If a string, only the specified file is extracted. + - **destination (str)**: The directory to extract files to. Defaults to the current directory. + - **show_compression_system_files (bool)**: If `True`, includes system files in the extraction. Defaults to `True`. + + ### Raises: + - **FileNotFoundError**: If the ZIP file does not exist. + - **ValueError**: If `extraction_list` is not `None`, a list, or a string. + - **Exception**: For any other errors that occur while reading the ZIP file. + + ### Examples: + - Extracts all contents of a ZIP file to the current directory: + ```python + read_zip_archive("/path/to/zipfile.zip") + ``` + + - Extracts specific files from a ZIP file to a specified directory: + ```python + read_zip_archive("/path/to/zipfile.zip", extraction_list=["file1.txt", "file2.txt"], destination="/path/to/destination") + ``` + + - Extracts a single file from a ZIP file: + ```python + read_zip_archive("/path/to/zipfile.zip", extraction_list="file1.txt", destination="/path/to/destination") + ``` + """ + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + if extraction_list is None: + zip_ref.extractall(destination) + elif isinstance(extraction_list, list): + for item in extraction_list: + zip_ref.extract(item, destination) + elif isinstance(extraction_list, str): + zip_ref.extract(extraction_list, destination) + else: + raise ValueError("The parameter 'extraction_list' must be None, a list, or a string.") + +def read_zip_archive(zip_filename, show_compression_system_files=True): + """ + # compression.zipfile.read_zip_archive(zip_filename, show_compression_system_files=True) + + --- + + ### Overview + Reads the contents of a ZIP file and returns a list of the names of the files contained within it. + + ### Parameters: + zip_filename (str): The path to the ZIP file to read. + + ### Returns: + list: A list of filenames contained in the ZIP file. + + ### Raises: + - FileNotFoundError: If the ZIP file does not exist. + - Exception: For any other errors that occur while reading the ZIP file. + + ### Examples: + - Reads the contents of a ZIP file and returns the list of filenames. + + ```python + list_contents("/path/to/zipfile.zip") + ``` + """ + try: + with zipfile.ZipFile(zip_filename, "r") as zip_file: + zip_contents_list = [] + all_contents_list = zip_file.namelist() + for i in all_contents_list: + if show_compression_system_files == True: + zip_contents_list.append(i) + else: + if "__MACOSX/" not in i: + if ".DS_Store" not in i: + zip_contents_list.append(i) + return zip_contents_list + except FileNotFoundError: + return "[FileSystem Pro]: File Not Found" + except Exception as e: + return f"[FileSystem Pro]: An error occurred. Error: {e}" diff --git a/filesystem/device/__init__.py b/filesystem/device/__init__.py new file mode 100644 index 0000000..1ab4f30 --- /dev/null +++ b/filesystem/device/__init__.py @@ -0,0 +1,90 @@ +""" +# Device + +--- + +## Overview + +The Device module provides a comprehensive set of functionalities for managing and retrieving various device-related information and metrics. This module is divided into two main parts: CPU Information and Disks Information. It leverages the `psutil` library to gather details efficiently and offers a wide range of functionalities for system monitoring and management tasks. + +## Features + +### CPU Information + +The CPU Information part of the module provides functionalities for retrieving various CPU-related information, such as CPU usage percentage, CPU times, and the number of CPU cores. It offers essential metrics for monitoring CPU performance. + +#### Functions: + +1. **cpu_percent** + - **Returns:** float - The CPU usage percentage. + +2. **cpu_times** + - **Returns:** psutil._pslinux.scputimes - An object containing the CPU times for the various states. + +3. **cpu_count** + - **Returns:** int - The number of logical CPU cores. + +### Disks Information + +The Disks Information part of the module provides functionalities for retrieving various disk-related information and metrics, such as disk partitions, boot drive names, filesystem types, and storage metrics. It also includes filtering capabilities to narrow down the information based on specific criteria. + +#### Disk Information + +1. **current_disk_filesystem_name** + - **Returns:** str - The filesystem type of the current disk. + +2. **boot_time** + - **Returns:** str - The boot time in the format `day/month/year hour:minute:second`. + +3. **get_disk_partitions** + - **Returns:** list - A list of dictionaries, each containing the attributes of a mounted disk partition. + +4. **get_boot_drive_name** + - **Returns:** str - The name of the boot drive on macOS. If the function is called on a non-macOS platform, it returns "NOT IMPLEMENTED". + +5. **get_disk_partition_filteredby_device** + - **Returns:** list - A list of dictionaries, each containing the attributes of a disk partition that matches the specified device filter. + +6. **get_disk_partition_filteredby_fstype** + - **Returns:** list - A list of dictionaries, each containing the attributes of a disk partition that matches the specified filesystem type filter. + +7. **get_disk_partition_filteredby_mountpoint** + - **Returns:** list - A list of dictionaries, each containing the attributes of a disk partition that matches the specified mount point filter. + +8. **get_disk_partition_filteredby_opts** + - **Returns:** list - A list of dictionaries, each containing the attributes of a disk partition that matches the specified options filter. + +#### Disk Usage + +1. **storage_metrics** + - **Returns:** dict - A dictionary containing storage metrics for a specific mount point. + +2. **disk_info** + - **Returns:** dict - A dictionary where each key is an index and each value is a tuple containing the attributes of a disk partition. + +3. **disk_io_counters** + - **Returns:** dict - A dictionary where each key is a disk name and each value is an object containing disk I/O statistics. + +## Detailed Functionality + +The module's functions are designed to be robust and easy to use, providing a high level of abstraction from the underlying device operations. + +### CPU Information + +The CPU Information part of the module provides essential metrics for monitoring CPU performance, including CPU usage percentage, CPU times for various states, and the number of logical CPU cores. + +### Disks Information + +The Disks Information part of the module provides comprehensive details about disk partitions, including devices, filesystem types, mount points, and options. It also offers storage metrics and disk I/O statistics, with filtering capabilities to narrow down the information based on specific criteria. + +## Usage + +To use the functions provided by this module, import the module and call the desired function with the appropriate parameters: + +```python +from filesystem import device +``` +""" + +from . import disks +from . import cpu \ No newline at end of file diff --git a/filesystem/device/cpu/__init__.py b/filesystem/device/cpu/__init__.py new file mode 100644 index 0000000..4c526dc --- /dev/null +++ b/filesystem/device/cpu/__init__.py @@ -0,0 +1,101 @@ +""" +# CPU + +--- + +## Overview + +The CPU module provides functionalities for retrieving CPU-related information such as CPU usage percentage, CPU times, and the number of CPU cores. It leverages the `psutil` library to gather these details efficiently. + +The CPU module is designed to provide essential CPU-related information for system monitoring and management tasks. +By utilizing the `psutil` library, it ensures accurate and efficient retrieval of CPU metrics. +""" + +import psutil + +def cpu_percent(): + """ + # cpu.cpu_percent() + + --- + + ### Overview + + Retrieves the system's CPU usage percentage. This function uses the `psutil.cpu_percent()` method to get the current CPU usage as a percentage. + + ### Parameters: + - **None** + + ### Returns: + - **float:** The CPU usage percentage. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the system's current CPU usage percentage. + + ```python + cpu_usage = cpu_percent() + print(cpu_usage) + ``` + """ + return psutil.cpu_percent() + +def cpu_times(): + """ + # cpu.cpu_times() + + --- + + ### Overview + + Retrieves CPU times for the system. This function uses the `psutil.cpu_times()` method to get the amount of time the CPU has spent in various states such as user, system, idle, etc. + + ### Parameters: + - **None** + + ### Returns: + - **psutil._pslinux.scputimes:** An object containing the CPU times for the various states. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the system's CPU times. + + ```python + cpu_times_info = cpu_times() + print(cpu_times_info) + ``` + """ + return psutil.cpu_times() + +def cpu_count(): + """ + # cpu.cpu_count() + + --- + + ### Overview + + Retrieves the number of CPU cores in the system. This function uses the `psutil.cpu_count()` method to get the total number of logical CPU cores available. + + ### Parameters: + - **None** + + ### Returns: + - **int:** The number of logical CPU cores. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the number of logical CPU cores in the system. + + ```python + num_cores = cpu_count() + print(num_cores) + ``` + """ + return psutil.cpu_count() \ No newline at end of file diff --git a/filesystem/device/disks/__init__.py b/filesystem/device/disks/__init__.py new file mode 100644 index 0000000..c61b5d2 --- /dev/null +++ b/filesystem/device/disks/__init__.py @@ -0,0 +1,772 @@ +""" +# Disks + +--- + +## Overview + +The Disks module provides a comprehensive set of functionalities for managing and retrieving various disk-related information and metrics. This module is divided into two main parts: Disk Information and Disk Usage. It leverages the `psutil` library to gather details efficiently and offers filtering capabilities to narrow down the information based on specific criteria. + +### Disk Information + +The Disk Information part of the module provides functionalities for retrieving various disk-related information, such as disk partitions, boot drive names, and filesystem types. It offers filtering capabilities to narrow down the information based on specific criteria. + +#### Functions: + +1. **current_disk_filesystem_name** + - **Returns:** str - The filesystem type of the current disk. + +2. **boot_time** + - **Returns:** str - The boot time in the format `day/month/year hour:minute:second`. + +3. **get_disk_partitions** + - **Returns:** list - A list of dictionaries, each containing the attributes of a mounted disk partition. + +4. **get_boot_drive_name** + - **Returns:** str - The name of the boot drive on macOS. If the function is called on a non-macOS platform, it returns "NOT IMPLEMENTED". + +5. **get_disk_partition_filteredby_device** + - **Returns:** list - A list of dictionaries, each containing the attributes of a disk partition that matches the specified device filter. + +6. **get_disk_partition_filteredby_fstype** + - **Returns:** list - A list of dictionaries, each containing the attributes of a disk partition that matches the specified filesystem type filter. + +7. **get_disk_partition_filteredby_mountpoint** + - **Returns:** list - A list of dictionaries, each containing the attributes of a disk partition that matches the specified mount point filter. + +8. **get_disk_partition_filteredby_opts** + - **Returns:** list - A list of dictionaries, each containing the attributes of a disk partition that matches the specified options filter. + +### Disk Usage + +The Disk Usage part of the module provides functionalities for retrieving various disk usage metrics, such as total, free, and used storage, as well as the percentage of free and used storage. It also includes functions for retrieving comprehensive information about the system's disk partitions and disk I/O counters. + +#### Functions: + +1. **storage_metrics** + - **Returns:** dict - A dictionary containing storage metrics for a specific mount point. + +2. **disk_info** + - **Returns:** dict - A dictionary where each key is an index and each value is a tuple containing the attributes of a disk partition. + +3. **disk_io_counters** + - **Returns:** dict - A dictionary where each key is a disk name and each value is an object containing disk I/O statistics. + +The Disks module is designed to provide essential disk-related information and usage metrics for system monitoring and management tasks. By utilizing the `psutil` library, it ensures accurate and efficient retrieval of disk metrics and attributes. +""" + +import psutil +from datetime import datetime +import subprocess +from sys import platform as PLATFORM + +def current_disk_filesystem_name(): + """ + # disks.current_disk_filesystem_name() + + --- + + ### Overview + + Retrieves the filesystem type of the current disk. This function checks the disk partitions and returns the filesystem type of the partition mounted at 'C:/' (for Windows) or '/' (for Unix-like systems). + + ### Parameters: + - **None** + + ### Returns: + - **str:** The filesystem type of the current disk. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the filesystem type of the current disk. + + ```python + filesystem_type = current_disk_filesystem_name() + print(filesystem_type) + ``` + """ + dskpart = psutil.disk_partitions() + fstypes = [part.fstype for part in dskpart if part.mountpoint in ['C:/', '/']] + + return fstypes[0] + +def boot_time(): + """ + # disks.boot_time() + + --- + + ### Overview + + Retrieves the system's boot time. This function uses the `psutil.boot_time()` method to get the boot time as a timestamp and then converts it to a human-readable format. + + ### Parameters: + - **None** + + ### Returns: + - **str:** The boot time in the format `day/month/year hour:minute:second`. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the system's boot time. + + ```python + boot_time_str = boot_time() + print(boot_time_str) + ``` + """ + boot_time_timestamp = psutil.boot_time() + bt = datetime.fromtimestamp(boot_time_timestamp) + return f'{bt.day}/{bt.month}/{bt.year} {bt.hour}:{bt.minute}:{bt.second}' + +######################################## DISK INFORMATION ######################################## + +### DISK PARTITIONS +def get_disk_partitions(): + """ + # disks.get_disk_partitions() + + --- + + ### Overview + + Retrieves a list of all mounted disk partitions and their attributes. This function converts the partition details into dictionary format for easier access and manipulation. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of dictionaries, each containing the attributes of a mounted disk partition. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of all mounted disk partitions. + + ```python + partitions = get_disk_partitions() + print(partitions) + ``` + """ + var = psutil.disk_partitions() + output = [part._asdict() for part in var] + return output + +def get_boot_drive_name(): + """ + # disks.get_boot_drive_name() + + --- + + ### Overview + + Retrieves the name of the boot drive on macOS. This function uses a subprocess call to the Foundation framework to obtain the display name of the boot drive. Note: This function is currently only implemented for macOS. + + ### Parameters: + - **None** + + ### Returns: + - **str:** The name of the boot drive on macOS. If the function is called on a non-macOS platform, it returns "NOT IMPLEMENTED". + + ### Raises: + - **Exception:** If an error occurs during the subprocess call, it returns the error message as a string. + + ### Examples: + - Retrieves the name of the boot drive on macOS. + + ```python + boot_drive_name = get_boot_drive_name() + print(boot_drive_name) + ``` + """ + if PLATFORM == "darwin": + try: + cmd = "python -c \"from Foundation import NSFileManager; print(NSFileManager.defaultManager().displayNameAtPath_('/'))\"" + startup_drive_name = subprocess.check_output(cmd, shell=True).decode("utf-8").strip() + return startup_drive_name + except Exception as e: + return str(e) + else: + return "NOT IMPLEMENTED" + +def get_disk_partition_filteredby_device(filter): + """ + # disks.get_disk_partition_filteredby_device(filter) + + --- + + ### Overview + + Filters and retrieves disk partitions based on the specified device. This function compares the device attribute of each partition with the provided filter and returns a list of matching partitions. + + ### Parameters: + - **filter (str):** The device name to filter the disk partitions by. + + ### Returns: + - **list:** A list of dictionaries, each containing the attributes of a disk partition that matches the specified device filter. + + ### Raises: + - **None** + + ### Examples: + - Filters disk partitions by the device name `sda1`. + + ```python + partitions = get_disk_partition_filteredby_device('sda1') + print(partitions) + ``` + """ + var = get_disk_partitions() + out_filter = filter.lower() + output = [d for d in var if d['device'] == out_filter] + return output + +def get_disk_partition_filteredby_fstype(filter): + """ + # disks.get_disk_partition_filteredby_fstype(filter) + + --- + + ### Overview + + Filters and retrieves disk partitions based on the specified filesystem type. This function compares the filesystem type attribute of each partition with the provided filter and returns a list of matching partitions. + + ### Parameters: + - **filter (str):** The filesystem type to filter the disk partitions by. + + ### Returns: + - **list:** A list of dictionaries, each containing the attributes of a disk partition that matches the specified filesystem type filter. + + ### Raises: + - **None** + + ### Examples: + - Filters disk partitions by the filesystem type `ext4`. + + ```python + partitions = get_disk_partition_filteredby_fstype('ext4') + print(partitions) + ``` + """ + var = get_disk_partitions() + out_filter = filter.lower() + output = [d for d in var if d['fstype'] == out_filter] + return output + +def get_disk_partition_filteredby_mountpoint(filter): + """ + # disks.get_disk_partition_filteredby_mountpoint(filter) + + --- + + ### Overview + + Filters and retrieves disk partitions based on the specified mount point. This function compares the mount point attribute of each partition with the provided filter and returns a list of matching partitions. + + ### Parameters: + - **filter (str):** The mount point to filter the disk partitions by. + + ### Returns: + - **list:** A list of dictionaries, each containing the attributes of a disk partition that matches the specified mount point filter. + + ### Raises: + - **None** + + ### Examples: + - Filters disk partitions by the mount point `/mnt/data`. + + ```python + partitions = get_disk_partition_filteredby_mountpoint('/mnt/data') + print(partitions) + ``` + """ + var = get_disk_partitions() + output = [d for d in var if d['mountpoint'] == filter] + return output + +def get_disk_partition_filteredby_opts(filter): + """ + # disks.get_disk_partition_filteredby_opts(filter) + + --- + + ### Overview + + Filters and retrieves disk partitions based on the specified options. This function compares the options attribute of each partition with the provided filter and returns a list of matching partitions. + + ### Parameters: + - **filter (str):** The options to filter the disk partitions by. + + ### Returns: + - **list:** A list of dictionaries, each containing the attributes of a disk partition that matches the specified options filter. + + ### Raises: + - **None** + + ### Examples: + - Filters disk partitions by the options `rw`. + + ```python + partitions = get_disk_partition_filteredby_opts('rw') + print(partitions) + ``` + """ + var = get_disk_partitions() + out_filter = filter.lower() + output = [d for d in var if d['opts'] == out_filter] + return output + +######################################## DISK USAGE ######################################## + +def storage_metrics(mountpoint): + """ + # disk.storage_metrics(mountpoint) + + --- + + ### Overview + + Returns storage metrics for a specific mount point, including total, free, and used storage, as well as the percentage of free and used storage. + + ### Parameters: + - **mountpoint (str):** The path of the mount point to get storage metrics for. + + ### Returns: + - **dict:** A dictionary containing storage metrics: + - `0`: Total storage. + - `1`: Free storage. + - `2`: Used storage. + - `3`: Percentage of free storage. + - `4`: Percentage of used storage. + + ### Raises: + - **None** + + ### Examples: + - Retrieves storage metrics for the root mount point. + + ```python + storage_metrics('/') + ``` + """ + var = psutil.disk_usage(mountpoint) + total = var.total + free = var.free + used = var.used + percent_free = var.percent + percent_used = 100 - float(var.percent) + + metrics_list = { + 0 : total, + 1 : free, + 2 : used, + 3 : percent_free, + 4 : percent_used + } + return metrics_list + +def disk_info(): + """ + # disks.disk_info() + + --- + + ### Overview + + Retrieves comprehensive information about the system's disk partitions, including devices, filesystem types, mount points, options, and storage metrics. This function consolidates data from multiple helper functions to provide detailed disk information. + + ### Parameters: + - **None** + + ### Returns: + - **dict:** A dictionary where each key is an index and each value is a tuple containing the attributes of a disk partition: + - Mount point + - Device + - Filesystem type + - Options + - Total storage + - Used storage + - Free storage + - Percentage of used storage + - Percentage of free storage + + ### Raises: + - **None** + + ### Examples: + - Retrieves detailed information about the system's disk partitions. + + ```python + disk_information = disk_info() + print(disk_information) + ``` + """ + def __get_disk_device_list__(): + """ + # disks.__get_disk_device_list__() + + --- + + ### Overview + + Retrieves a list of all disk devices from the system's disk partitions. This function processes the partitions and extracts the device attribute from each partition to create a list of disk devices. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of disk devices. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of all disk devices. + + ```python + device_list = __get_disk_device_list__() + print(device_list) + ``` + """ + var = get_disk_partitions() + data_list = [] + for data in var: + data_list.append(data) + devices = [item['device'] for item in data_list] + return devices + + def __get_disk_filesystem_list__(): + """ + # disks.__get_disk_filesystem_list__() + + --- + + ### Overview + + Retrieves a list of all filesystem types from the system's disk partitions. This function processes the partitions and extracts the filesystem type attribute from each partition to create a list of filesystem types. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of filesystem types. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of all filesystem types. + + ```python + fstypes = __get_disk_filesystem_list__() + print(fstypes) + ``` + """ + var = get_disk_partitions() + data_list = [] + for data in var: + data_list.append(data) + fstype = [item['fstype'] for item in data_list] + return fstype + + def __get_disk_mountpoint_list__(): + """ + # disks.__get_disk_mountpoint_list__() + + --- + + ### Overview + + Retrieves a list of all mount points from the system's disk partitions. This function processes the partitions and extracts the mount point attribute from each partition to create a list of mount points. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of mount points. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of all mount points. + + ```python + mountpoints = __get_disk_mountpoint_list__() + print(mountpoints) + ``` + """ + var = get_disk_partitions() + data_list = [] + for data in var: + data_list.append(data) + mountpoints = [item['mountpoint'] for item in data_list] + return mountpoints + + def __get_disk_opts_list__(): + """ + # disks.__get_disk_opts_list__() + + --- + + ### Overview + + Retrieves a list of all options from the system's disk partitions. This function processes the partitions and extracts the options attribute from each partition to create a list of options. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of options. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of all options. + + ```python + opts = __get_disk_opts_list__() + print(opts) + ``` + """ + var = get_disk_partitions() + data_list = [] + for data in var: + data_list.append(data) + opts = [item['opts'] for item in data_list] + return opts + + def __get_disk_total_usage_list__(): + """ + # disks.__get_disk_total_usage_list__() + + --- + + ### Overview + + Retrieves a list of total storage usage for all disk partitions. This function processes the list of mount points, calculates the total storage for each partition using the `storage_metrics` function, and returns a list of total storage values. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of total storage values for each disk partition. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of total storage usage for all disk partitions. + + ```python + total_usage = __get_disk_total_usage_list__() + print(total_usage) + ``` + """ + var = __get_disk_mountpoint_list__() + total_list = [] + for disk in var: + metrics = storage_metrics(disk) + total_list.append(metrics[0]) + return total_list + + def __get_disk_free_usage_list__(): + """ + # disks.__get_disk_free_usage_list__() + + --- + + ### Overview + + Retrieves a list of free storage usage for all disk partitions. This function processes the list of mount points, calculates the free storage for each partition using the `storage_metrics` function, and returns a list of free storage values. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of free storage values for each disk partition. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of free storage usage for all disk partitions. + + ```python + free_usage = __get_disk_free_usage_list__() + print(free_usage) + ``` + """ + var = __get_disk_mountpoint_list__() + free_list = [] + for disk in var: + metrics = storage_metrics(disk) + free_list.append(metrics[1]) + return free_list + + def __get_disk_used_usage_list__(): + """ + # disks.__get_disk_used_usage_list__() + + --- + + ### Overview + + Retrieves a list of used storage usage for all disk partitions. This function processes the list of mount points, calculates the used storage for each partition using the `storage_metrics` function, and returns a list of used storage values. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of used storage values for each disk partition. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of used storage usage for all disk partitions. + + ```python + used_usage = __get_disk_used_usage_list__() + print(used_usage) + ``` + """ + var = __get_disk_mountpoint_list__() + used_list = [] + for disk in var: + metrics = storage_metrics(disk) + used_list.append(metrics[2]) + return used_list + + def __get_disk_free_percent_usage_list__(): + """ + # disks.__get_disk_free_percent_usage_list__() + + --- + + ### Overview + + Retrieves a list of free storage percentage usage for all disk partitions. This function processes the list of mount points, calculates the percentage of free storage for each partition using the `storage_metrics` function, and returns a list of free storage percentages. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of free storage percentages for each disk partition. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of free storage percentage usage for all disk partitions. + + ```python + free_percent_usage = __get_disk_free_percent_usage_list__() + print(free_percent_usage) + ``` + """ + var = __get_disk_mountpoint_list__() + free_percent_list = [] + for disk in var: + metrics = storage_metrics(disk) + free_percent_list.append(metrics[3]) + return free_percent_list + + def __get_disk_used_percent_usage_list__(): + """ + # disks.__get_disk_used_percent_usage_list__() + + --- + + ### Overview + + Retrieves a list of used storage percentage usage for all disk partitions. This function processes the list of mount points, calculates the percentage of used storage for each partition using the `storage_metrics` function, and returns a list of used storage percentages. + + ### Parameters: + - **None** + + ### Returns: + - **list:** A list of used storage percentages for each disk partition. + + ### Raises: + - **None** + + ### Examples: + - Retrieves the list of used storage percentage usage for all disk partitions. + + ```python + used_percent_usage = __get_disk_used_percent_usage_list__() + print(used_percent_usage) + ``` + """ + var = __get_disk_mountpoint_list__() + used_percent_list = [] + for disk in var: + metrics = storage_metrics(disk) + used_percent_list.append(metrics[4]) + return used_percent_list + + devices = __get_disk_device_list__() + filesystems = __get_disk_filesystem_list__() + mountpoint = __get_disk_mountpoint_list__() + opts = __get_disk_opts_list__() + total = __get_disk_total_usage_list__() + used = __get_disk_used_usage_list__() + free = __get_disk_free_usage_list__() + percent_used = __get_disk_used_percent_usage_list__() + percent_free = __get_disk_free_percent_usage_list__() + + disk_info = {i: info for i, info in enumerate( + zip(mountpoint, devices, filesystems, + opts, total, used, free, percent_used, percent_free) + ) + } + return disk_info + +def disk_io_counters(): + """ + # disks.disk_io_counters() + + --- + + ### Overview + + Retrieves disk I/O statistics for each disk in the system. This function utilizes the `psutil.disk_io_counters` method to gather I/O counters for each disk, including the number of read and write operations, the number of bytes read and written, and the time spent reading and writing. + + ### Parameters: + - **None** + + ### Returns: + - **dict:** A dictionary where each key is a disk name and each value is an object containing disk I/O statistics. + + ### Raises: + - **None** + + ### Examples: + - Retrieves disk I/O statistics for all disks. + + ```python + io_counters = disk_io_counters() + print(io_counters) + ``` + """ + disk_io = psutil.disk_io_counters(perdisk=True) + return disk_io + +######################################## DISK INFORMATION ######################################## + +drive_name = get_boot_drive_name() +""" +The name of the boot drive on macOS. +This function uses a subprocess call to the Foundation framework to obtain +the display name of the boot drive. +Note: This function is currently only implemented for macOS. + +If the function is called on a non-macOS platform, it returns "NOT IMPLEMENTED". +""" \ No newline at end of file diff --git a/filesystem/directory/__init__.py b/filesystem/directory/__init__.py index 9c222d9..4a91641 100644 --- a/filesystem/directory/__init__.py +++ b/filesystem/directory/__init__.py @@ -236,9 +236,9 @@ def exists(path): return True return False -def get_directories(path, fullpath=False): +def get_directories(path, fullpath=True): """ - # directory.get_directories(path, fullpath=False) + # directory.get_directories(path, fullpath=True) --- @@ -247,7 +247,7 @@ def get_directories(path, fullpath=False): ### Parameters: path (str): The directory path to search within. - fullpath (bool, optional): If True, returns the full path of each directory. Defaults to False. + fullpath (bool, optional): If True, returns the full path of each directory. Defaults to True. ### Returns: list: A list of directory names or full paths, depending on the `fullpath` parameter. @@ -374,6 +374,46 @@ def get_parent_name(path): return os.path.basename(path) return os.path.basename(os.path.dirname(path)) +def get_size(directory_path): + """ + # directory.get_size(directory_path) + + --- + + ### Overview + Calculates the total size of all files in the specified directory. The size is returned in bytes, KB, MB, GB, or TB, depending on the total size. + + ### Parameters: + - directory_path (str): The path of the directory to calculate the size of. + + ### Returns: + - str: A string representing the total size of the directory, formatted as a float followed by the unit of measurement. + + ### Raises: + - FileNotFoundError: If the directory does not exist. + - PermissionError: If permission is denied. + + ### Examples: + - Calculate the total size of all files in a directory: + + ```python + get_size("/path/to/directory") + + """ + if not os.path.isdir(directory_path): + raise FileNotFoundError(f"O diretório '{directory_path}' não foi encontrado.") + + total_size = sum( + os.path.getsize(os.path.join(dirpath, filename)) + for dirpath, dirnames, filenames in os.walk(directory_path) + for filename in filenames + ) + + for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']: + if total_size < 1024.0: + return f"{total_size:3.1f} {unit}" + total_size /= 1024.0 + def join(path1='', path2='', path3='', path4='', paths=[]): """ # directory.join(path1='', path2='', path3='', path4='', paths=[]) diff --git a/filesystem/file/__init__.py b/filesystem/file/__init__.py index 2b8f7a5..cf01b81 100644 --- a/filesystem/file/__init__.py +++ b/filesystem/file/__init__.py @@ -90,7 +90,7 @@ def append_text(file, text): ``` """ with open(file, 'a', encoding='utf-8') as file: - file.write(text + '\n') + file.write(f'{text}') def calculate_checksum(file): """ @@ -121,7 +121,6 @@ def calculate_checksum(file): """ sha256_hash = hashlib.sha256() with open(file, "rb") as f: - # Read and update hash in chunks of 4K for byte_block in iter(lambda: f.read(4096), b""): sha256_hash.update(byte_block) return sha256_hash.hexdigest() @@ -159,46 +158,49 @@ def check_integrity(file, reference_file): return file_to_check == reference_check -def create(file, data, encoding="utf-8"): +def create(file, data, overwrite=False, encoding="utf-8"): """ - # file.create(file, data, encoding="utf-8") + # file.create(file, data, overwrite=False, encoding="utf-8") --- - + ### Overview - Creates a file at the specified path and writes data into it. If the file already exists, - its contents are overwritten. The function then returns the details of the created file. + Creates a file at the specified path and writes data into it. If the file already exists, its contents can be either appended to or overwritten based on the `overwrite` parameter. The function then returns the details of the created file. ### Parameters: - file (str): The file path to create. - data (str): The data to write into the file. - encoding (str): The encoding to use when opening the file. Defaults to "utf-8". + - **file (str)**: The file path to create. + - **data (str)**: The data to write into the file. + - **overwrite (bool)**: Whether to overwrite the file if it already exists. Defaults to `False`. + - **encoding (str)**: The encoding to use when opening the file. Defaults to "utf-8". ### Returns: - dict: A dictionary containing the details of the created file. + - **dict**: A dictionary containing the details of the created file. ### Raises: - - FileNotFoundError: If the file does not exist. - - PermissionError: If the permission is denied. - - UnicodeEncodeError: If the data cannot be encoded with the specified encoding. + - **FileNotFoundError**: If the file does not exist. + - **PermissionError**: If the permission is denied. + - **UnicodeEncodeError**: If the data cannot be encoded with the specified encoding. ### Examples: - Creates a file and writes data into it, then returns the file details. - ```python - create("/path/to/file", "Hello, World!") - ``` + ```python + create("/path/to/file", "Hello, World!") + ``` + - Creates a file with a different encoding, writes data into it, then returns the file details. - ```python - create("/path/to/file", "Hello, World!", "utf-16") - ``` + ```python + create("/path/to/file", "Hello, World!", overwrite=True, encoding="utf-16") + ``` """ - try: + if overwrite==True: with codecs.open(f'{file}', "w", encoding=encoding) as custom_file: custom_file.write(data) - except: - pass + else: + with codecs.open(f'{file}', "a", encoding=encoding) as custom_file: + custom_file.write(data) + return wra.get_object(f'{file}') def create_binary_file(filename, data): @@ -340,6 +342,50 @@ def exists(file): return True return False +def find_duplicates(path): + """ + # file.find_duplicates(path) + + --- + + ### Overview + Finds duplicate files in a given directory and its subdirectories. + A file is considered a duplicate if it has the same checksum as another file. + + ### Parameters: + path (str): The directory path to search for duplicate files. + + ### Returns: + A tuple of two lists: + - The first list contains the paths of the original files. + - The second list contains the paths of the duplicate files. + + ### Raises: + - FileNotFoundError: If the directory does not exist. + - PermissionError: If the permission is denied. + + ### Examples: + - Finds duplicate files in a specific directory. + + ```python + find_duplicates("/path/to/directory") + ``` + """ + checksums = {} + original_files = [] + duplicate_files = [] + + for root, dirs, files in os.walk(path): + for file in files: + file_path = dir.join(root, file) + checksum = calculate_checksum(file_path) + if checksum in checksums: + original_files.append(checksums[checksum]) + duplicate_files.append(file_path) + else: + checksums[checksum] = file_path + return original_files, duplicate_files + def get_extension(file_path, lower=True): """ # file.get_extension(file_path, lower=True) @@ -377,9 +423,9 @@ def get_extension(file_path, lower=True): return file_extension.lower() return file_extension.upper() -def get_files(path, fullpath=False, extension=None): +def get_files(path, fullpath=True, extension=None): """ - # file.get_files(path, fullpath=False, extension=None) + # file.get_files(path, fullpath=True, extension=None) --- @@ -388,7 +434,7 @@ def get_files(path, fullpath=False, extension=None): ### Parameters: - path (str): The directory path to search for files. - - fullpath (bool, optional): If True, returns the full path of each file. Defaults to False. + - fullpath (bool, optional): If True, returns the full path of each file. Defaults to True. - extension (str, optional): If specified, only files with this extension will be included. Defaults to None. ### Returns: @@ -422,6 +468,42 @@ def get_files(path, fullpath=False, extension=None): file_list.append(file) return file_list +def get_size(file_path): + """ + # file.get_size(file_path) + + --- + + ### Overview + Calculates the size of a file at the specified path. + The size is returned in bytes, KB, MB, GB, or TB, depending on the size. + + ### Parameters: + - file_path (str): The path of the file to calculate the size of. + + ### Returns: + - str: A string representing the size of the file, formatted as a float followed by the unit of measurement. + + ### Raises: + - FileNotFoundError: If the file does not exist. + - PermissionError: If the permission is denied. + + ### Examples: + - Calculate the size of a file: + + ```python + get_size("/path/to/file") + """ + + if not os.path.isfile(file_path): + raise FileNotFoundError(f"O arquivo '{file_path}' não foi encontrado.") + + size = os.path.getsize(file_path) + for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']: + if size < 1024.0: + return f"{size:3.1f} {unit}" + size /= 1024.0 + def move(source, destination, new_filename=None, replace_existing=False): """ # file.move(source, destination, new_filename=None, replace_existing=False) diff --git a/filesystem/watcher/__init__.py b/filesystem/watcher/__init__.py index d19e4a2..6d0ab75 100644 --- a/filesystem/watcher/__init__.py +++ b/filesystem/watcher/__init__.py @@ -96,7 +96,6 @@ def diff(self): i["change"] = "removed" results.append(i) - # set new state self.saved_state = current_state return results diff --git a/filesystem/wrapper/__init__.py b/filesystem/wrapper/__init__.py index 45b02a2..7139db1 100644 --- a/filesystem/wrapper/__init__.py +++ b/filesystem/wrapper/__init__.py @@ -6,12 +6,11 @@ ## Overview Wrapper is an integral part of the FileSystemPro library, designed to provide detailed information about files and directories. -It includes functions for retrieving metadata, checking file extensions, and creating zip archives. +It includes functions for retrieving metadata and checking file extensions. ## Features - `Metadata Retrieval:` Gathers comprehensive metadata about a file or directory path. - `Extension Check:` Determines whether a file has an extension. -- `Zip Archive Creation:` Packages a directory or file into a zip archive. ## Detailed Functionality The module's functions are crafted to offer detailed insights into the file system and to perform common @@ -27,11 +26,6 @@ The `has_extension` function checks if a given file path has an extension, which is useful for file type validation or processing logic that depends on file types. -### Zip Archive Creation (`make_zip`) -The `make_zip` function creates a zip archive from the specified source directory or file and -saves it to the given destination. -It is a convenient way to compress and package files for storage or transfer. - ## Usage To use the functions provided by this module, import the module and call the desired function with the appropriate parameters: @@ -42,328 +36,10 @@ """ -import codecs import datetime -import glob import os -import shutil from filesystem import file as fsfile from filesystem import directory as dir -import zipfile - -### wrapper.combine() kept to cover version support. Remove on (MAJOR UPDATE ONLY) -def combine(*args, paths=[]): - """ - # wrapper.combine(*args, paths=[]) - - #### Under support - - Consider using `directory.combine(*args, paths=[])` - - --- - - ### Overview - Combines a list of paths or arguments into a single path. If the first argument or the first element in the paths list is not an absolute path, it raises a ValueError. - - ### Parameters: - *args (str): The paths to combine. The first argument must be an absolute path. - paths (list): A list of paths to combine. The first element in the list must be an absolute path. Defaults to an empty list. - - ### Returns: - str: The combined path. - - ### Raises: - - ValueError: If the first argument or the first element in the paths list is not an absolute path. - - ### Examples: - - Combines all paths in the list, starting with an absolute path. - - ```python - combine(paths=["/home/user/directory", "subdirectory", "file.txt"]) - ``` - - Combines all arguments, starting with an absolute path. - - ```python - combine("/home/user/directory", "subdirectory", "file.txt") - ``` - """ - if paths: - result = paths[0] - if not os.path.isabs(result): - raise ValueError( -f'''Invalid argument: The path "{result}" is not an absolute path. -- The first argument inside paths list must to be an absolute path. - -For example, "/home/user/directory" is a valid absolute path. Please provide a valid absolute path. - -''' -) - for path in paths: - if os.path.isabs(path): - result = path - else: - result = join(result, path) - return result - - result = args[0] - if not os.path.isabs(result): - raise ValueError( -f'''Invalid argument: The path "{result}" is not an absolute path. -- The first argument must to be an absolute path. - -For example, "/home/user/directory" is a valid absolute path. Please provide a valid absolute path. - -''' -) - for path in args[1:]: - if path == '': - continue - if os.path.isabs(path): - result = path - else: - if not result.endswith(os.sep): - result += os.sep - result += path - return result - -### wrapper.create_directory() kept to cover version support. Remove on (MAJOR UPDATE ONLY) -def create_directory(path, create_subdirs=True): - """ - # wrapper.create(path, create_subdirs = True) - - #### Under support - - Consider using `directory.create(path, create_subdirs = True)` - --- - - ### Overview - Creates a directory at the specified path. If `create_subdirs` is True, all intermediate-level - directories needed to contain the leaf directory will be created. This function is useful for - setting up directory structures in a file system. - - ### Parameters: - - path (str): The directory path to create. - - create_subdirs (bool): A flag that indicates whether to create intermediate subdirectories. - Defaults to True. - - ### Returns: - None - - ### Raises: - - PermissionError: If the permission is denied. - - ### Examples: - - Creates all intermediate subdirectories if they don't exist. - - ```python - create("/path/to/directory") - ``` - - Creates only the leaf directory, raises an error if any intermediate directory doesn't exist. - - ```python - create("/path/to/directory", False) - ``` - """ - if create_subdirs: - os.makedirs(path, exist_ok=True) - else: - os.mkdir(path) - return get_object(path) - -### wrapper.create_file() kept to cover version support. Remove on (MAJOR UPDATE ONLY) -def create_file(file_name, path, text, encoding="utf-8-sig"): - """ - # create_file(file_name, path, text, encoding="utf-8-sig") - - #### Under support - - Consider using `file.create(file, data, encoding="utf-8-sig")` - --- - - ### Overview - Creates a file with a specified name, path, and text content. - The file is created with a specified encoding, defaulting to "utf-8-sig". - - ### Parameters: - file_name (str): The name of the file to create. - path (str): The directory path where the file will be created. - text (str): The text content to write into the file. - encoding (str): The encoding to use when creating the file. Defaults to "utf-8-sig". - - ### Returns: - A dictionary containing various attributes of the created file. These attributes include the time of last modification, creation time, last access time, name, size, absolute path, parent directory, whether it's a directory or file or link, whether it exists, and its extension. - - ### Raises: - - FileExistsError: If the file already exists. - - PermissionError: If the permission is denied. - - ### Examples: - - Creates a file with specified text content. - - ```python - create_file("example.txt", "/path/to/directory", "Hello, World!") - ``` - """ - try: - with codecs.open(f'{path}/{file_name}', "w", encoding=encoding) as custom_file: - custom_file.write(text) - except: - pass - return get_object(f'{path}/{file_name}') - -### wrapper.delete() kept to cover version support. Remove on (MAJOR UPDATE ONLY) -def delete(path, recursive=False): - """ - # wrapper.delete(path, recursive = False) - - #### Under support - - Consider using `directory.delete(path, recursive=False)` - - --- - - ### Overview - Deletes a directory at the specified path. If `recursive` is True, the directory and all its contents will be removed. - - ### Parameters: - path (str): The directory path to delete. - recursive (bool): A flag that indicates whether to delete the directory even if it is not empty. Defaults to False. - - ### Returns: - None - - ### Raises: - - Exception: If the directory does not exist or if the directory is not empty and `recursive` is False. - - ### Examples: - - Deletes an empty directory. - - ```python - delete("/path/to/directory") - ``` - - Deletes a directory and all its contents. - - ```python - delete("/path/to/directory", True) - ``` - """ - if not os.path.exists(path): - raise Exception(f'\n\n>> The directory "{path}" does not exist.') - - if not os.listdir(path) or recursive: - shutil.rmtree(path) - else: - raise Exception(f'\n\n>> The directory "{path}" is not empty.\n>> Use delete(path, True) to remove anyway.') - -### wrapper.enumerate_files() kept to cover version support. Remove on (MAJOR UPDATE ONLY) -def enumerate_files(path): - """ - # wrapper.enumerate_files(file) - - #### Under support - - Consider using `file.enumerate_files(path)` - --- - - ### Overview - Enumerates all files in a given directory and its subdirectories. For each file and directory, it retrieves various attributes using the `wra.get_object` function. - - ### Parameters: - file (str): The directory path to enumerate files from. - - ### Returns: - A list of dictionaries, where each dictionary contains various attributes of a file or directory. These attributes include the time of last modification, creation time, last access time, name, size, absolute path, parent directory, whether it's a directory or file or link, whether it exists, and its extension (if it's a file). - - ### Raises: - - FileNotFoundError: If the directory does not exist. - - PermissionError: If the permission is denied. - - ### Examples: - - Enumerates all files in the home directory and its subdirectories. - - ```python - enumerate_files("~/") - ``` - """ - results = [] - path = os.path.expanduser(path) - for root, dirs, files in os.walk(path): - results.append(get_object(root)) - results.extend([get_object(join(root,x)) for x in files]) - return results - -def find_duplicates(path): - """ - # wrapper.find_duplicates(path) - - --- - - ### Overview - Finds duplicate files in a given directory and its subdirectories. - A file is considered a duplicate if it has the same checksum as another file. - - ### Parameters: - path (str): The directory path to search for duplicate files. - - ### Returns: - A tuple of two lists: - - The first list contains the paths of the original files. - - The second list contains the paths of the duplicate files. - - ### Raises: - - FileNotFoundError: If the directory does not exist. - - PermissionError: If the permission is denied. - - ### Examples: - - Finds duplicate files in a specific directory. - - ```python - find_duplicates("/path/to/directory") - ``` - """ - checksums = {} - original_files = [] - duplicate_files = [] - - for root, dirs, files in os.walk(path): - for file in files: - file_path = dir.join(root, file) - checksum = fsfile.calculate_checksum(file_path) - if checksum in checksums: - original_files.append(checksums[checksum]) - duplicate_files.append(file_path) - else: - checksums[checksum] = file_path - return original_files, duplicate_files - -### wrapper.get_files() kept to cover version support. Remove on (MAJOR UPDATE ONLY) -def get_files(path): - """ - # wrapper.get_files(path) - - #### Under support - - Consider using `file.get_files(path)` - - --- - ### Overview - Returns a list of dictionaries, each representing the properties of a file or directory at the specified path. - - ### Parameters: - path (str): The path to get files from. This can be a directory or a file. - - ### Returns: - A list of dictionaries. Each dictionary represents the properties of a file or directory and is obtained by calling the `get_object` function. - - ### Raises: - - FileNotFoundError: If the path does not exist. - - PermissionError: If the permission is denied. - - ### Examples: - - Get properties for all files in a directory. - - ```python - get_files("/path/to/directory") - ``` - - Get properties for a single file. - - ```python - get_files("/path/to/file.txt") - ``` - """ - result = [] - path = os.path.expanduser(path) - for x in glob.glob(path): - result.append(get_object(x)) - return result def get_object(path): """ @@ -508,6 +184,50 @@ def obj_last_access_date(path): formatted_date = access_date.strftime("%Y/%m/%d %H:%M:%S:%f") return formatted_date + def obj_get_size(path): + """ + ### Overview + Calculates the size of the file or directory at the specified path. If the path is a directory, + it calculates the total size of all files in the directory. The size is returned in bytes, KB, + MB, GB, or TB, depending on the size. + + ### Parameters: + path (str): The file or directory path to calculate the size of. + + ### Returns: + str: A string representing the size of the file or directory, formatted as a float followed by + the unit of measurement. + + ### Raises: + - FileNotFoundError: If the file or directory does not exist. + - PermissionError: If the permission is denied. + + ### Examples: + - Calculates the size of a file. + + ```python + get_size("/path/to/file") + ``` + - Calculates the total size of all files in a directory. + + ```python + get_size("/path/to/directory") + ``` + """ + if os.path.isfile(path): + size = os.path.getsize(path) + else: + size = sum( + os.path.getsize(os.path.join(dirpath, filename)) + for dirpath, dirnames, filenames in os.walk(path) + for filename in filenames + ) + + for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']: + if size < 1024.0: + return f"{size:3.1f} {unit}" + size /= 1024.0 + head, tail = os.path.split(path) result = {} @@ -520,62 +240,12 @@ def obj_last_access_date(path): result["is_file"] = os.path.isfile(path) result["is_link"] = os.path.islink(path) result["extension"] = tail.split(".")[-1] if result["is_file"] else "" - ### EXT kept to cover version support. Remove on (MAJOR UPDATE ONLY) - result["ext"] = tail.split(".")[-1] if result["is_file"] else "" result["modified"] = obj_modification_date(path) result["name"] = tail result["name_without_extension"] = tail.split('.')[0] - result["size"] = get_size(path) + result["size"] = obj_get_size(path) return result -def get_size(file_path): - """ - # wrapper.get_size(path) - - --- - - ### Overview - Calculates the size of the file or directory at the specified path. If the path is a directory, - it calculates the total size of all files in the directory. The size is returned in bytes, KB, - MB, GB, or TB, depending on the size. - - ### Parameters: - path (str): The file or directory path to calculate the size of. - - ### Returns: - str: A string representing the size of the file or directory, formatted as a float followed by - the unit of measurement. - - ### Raises: - - FileNotFoundError: If the file or directory does not exist. - - PermissionError: If the permission is denied. - - ### Examples: - - Calculates the size of a file. - - ```python - get_size("/path/to/file") - ``` - - Calculates the total size of all files in a directory. - - ```python - get_size("/path/to/directory") - ``` - """ - if os.path.isfile(file_path): - size = os.path.getsize(file_path) - else: - size = sum( - os.path.getsize(os.path.join(dirpath, filename)) - for dirpath, dirnames, filenames in os.walk(file_path) - for filename in filenames - ) - - for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']: - if size < 1024.0: - return f"{size:3.1f} {unit}" - size /= 1024.0 - def has_extension(file_path): """ # wrapper.has_extension(file_path) @@ -607,201 +277,3 @@ def has_extension(file_path): This will return False because the file does not have an extension. """ return os.path.splitext(file_path)[1] != '' - -### wrapper.join() kept to cover version support. Remove on (MAJOR UPDATE ONLY) -def join(path1='', path2='', path3='', path4='', paths=[]): - """ - # wrapper.join(path1='', path2='', path3='', path4='', paths=[]) - - #### Under support - - Consider using `directory.join(path1='', path2='', path3='', path4='', paths=[])` - --- - - ### Overview - Joins multiple directory paths into a single path. The function ensures that each directory path ends with a separator before joining. If a directory path does not end with a separator, one is added. - - ### Parameters: - path1, path2, path3, path4 (str): The directory paths to join. Defaults to an empty string. - paths (list): A list of additional directory paths to join. Defaults to an empty list. - - ### Returns: - str: The joined directory path. - - ### Examples: - - Joins multiple directory paths. - - ```python - join("/path/to", "directory", paths=["subdirectory", "file.txt"]) - ``` - - Joins multiple directory paths without additional paths. - - ```python - join("/path/to", "directory") - ``` - """ - key_dir = "" - if not path1.endswith(os.sep): - if path1 != "": - path1 = path1 + os.sep - key_dir += path1 - if not path2.endswith(os.sep): - if path2 != "": - path2 = path2 + os.sep - key_dir += path2 - if not path3.endswith(os.sep): - if path3 != "": - path3 = path3 + os.sep - key_dir += path3 - if not path4.endswith(os.sep): - if path4 != "": - path4 = path4 + os.sep - key_dir += path4 - - if paths: - for item in paths: - if not item.endswith(os.sep): - item = item + os.sep - key_dir += item - return key_dir[:-1] - -### wrapper.list_directories() kept to cover version support. Remove on (MAJOR UPDATE ONLY) -def list_directories(path): - """ - # wrapper.list_directories(path) - - #### Under support - - Consider using `directory.get_directories(path)` - - --- - - ### Overview - Lists all directories in the specified path. - - ### Parameters: - path (str): The directory path to list. - - ### Returns: - list: A list of directory names in the specified path. - - ### Examples: - - Lists all directories in a specific path. - - ```python - get_directories("/path/to/directory") - ``` - """ - directory_list = [] - for dir in os.listdir(path): - if os.path.isdir(join(path, dir)): - directory_list.append(dir) - - return directory_list - -### wrapper.list_files() kept to cover version support. Remove on (MAJOR UPDATE ONLY) -def list_files(path): - """ - # wrapper.list_files(path) - - #### Under support - - Consider using `file.get_files(path)` - - --- - - ### Overview - Retrieves all files in a given directory. - - ### Parameters: - path (str): The directory path to retrieve files from. - - ### Returns: - A list of strings, where each string is the name of a file in the directory. - - ### Raises: - - FileNotFoundError: If the directory does not exist. - - PermissionError: If the permission is denied. - - ### Examples: - - Retrieves all files in a specific directory. - - ```python - get_files("/path/to/directory") - ``` - """ - file_list = [] - for file in os.listdir(path): - if os.path.isfile(join(path, file)): - file_list.append(file) - return file_list - -def make_zip(source, destination): - """ - # wrapper.make_zip(source, destination) - - --- - - ### Overview - Creates a zip archive of the specified source directory or file and moves it to the specified destination. - - ### Parameters: - source (str): The path of the directory or file to archive. - destination (str): The path where the archive will be moved to. - - ### Returns: - None - - ### Raises: - - FileNotFoundError: If the source file or directory does not exist. - - PermissionError: If the permission is denied. - - shutil.SameFileError: If source and destination are the same file. - - ### Examples: - - Creates a zip archive of a directory and moves it to a destination. - - ```python - make_zip("/path/to/directory", "/path/to/directory.zip") - ``` - - Creates a zip archive of a file and moves it to a destination. - - ```python - make_zip("/path/to/file.txt", "/path/to/file.zip") - ``` - """ - base = os.path.basename(destination) - name = base.split('.')[0] - format = base.split('.')[1] - archive_from = os.path.dirname(source) - archive_to = os.path.basename(source.strip(os.sep)) - shutil.make_archive(name, format, archive_from, archive_to) - shutil.move('%s.%s'%(name,format), destination) - -def read_zip_file_contents(zip_filename): - """ - # wrapper.read_zip_file_contents(zip_filename) - - --- - - ### Overview - Reads the contents of a ZIP file and returns a list of the names of the files contained within it. - - ### Parameters: - zip_filename (str): The path to the ZIP file to read. - - ### Returns: - list: A list of filenames contained in the ZIP file. - - ### Raises: - - FileNotFoundError: If the ZIP file does not exist. - - Exception: For any other errors that occur while reading the ZIP file. - - ### Examples: - - Reads the contents of a ZIP file and returns the list of filenames. - - ```python - read_zip_file_contents("/path/to/zipfile.zip") - ``` - """ - try: - with zipfile.ZipFile(zip_filename, "r") as zip_file: - zip_contents_list = zip_file.namelist() - return zip_contents_list - except FileNotFoundError: - return "[FileSystem Pro]: File Not Found" - except Exception as e: - return f"[FileSystem Pro]: An error occurred. Error: {e}" diff --git a/pyproject.toml b/pyproject.toml index 171a270..2338118 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,9 +1,9 @@ [build-system] -requires = ["setuptools", "wheel"] +requires = ["setuptools", "wheel", "requests", "psutil"] [tool.poetry] name = "FileSystemPro" -version = "1.0.4.0" +version = "2.0.0.0" description = "FileSystemPro is a powerful toolkit designed to handle file and directory operations with ease and efficiency across various operating systems." authors = ["Heitor Bisneto "] diff --git a/setup.py b/setup.py index 5148dab..e3b1541 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name = 'filesystempro', - version = '1.0.4.0', + version = '2.0.0.0', url = 'https://github.com/hbisneto/FileSystemPro', license = 'MIT License', @@ -31,21 +31,19 @@ description = u'FileSystemPro is a powerful toolkit designed to handle file and directory operations with ease and efficiency across various operating systems.', install_requires = [ 'requests', + 'psutil', ], long_description = readme, long_description_content_type = "text/markdown", - keywords = ['FileSystem', + keywords = ['Compression', 'Console', 'Device', + 'Directory', + 'File', 'FileSystem', 'Linux', 'macOS', - 'Windows', - 'File', 'System', 'Terminals', - 'Console', - 'Directory', - 'Watcher', - 'Wrapper' - ], + 'Watcher', 'Windows', 'Wrapper' + ], packages=find_packages(), platforms = 'any', python_requires= '>=3.8',