### Size Filter Configuration Examples Source: https://organize.readthedocs.io/en/latest/filters YAML configuration examples demonstrating how to use the size filter within organize rules to manage files based on size thresholds. ```yaml rules: - locations: "~/Downloads" targets: files filters: - size: "> 0.5 GB" actions: - trash - locations: - path: "~/Pictures" max_depth: null filters: - extension: - jpg - jpeg - size: ">1mb, <10mb" actions: - move: "~/Pictures/sorted/{relative_path}/" ``` -------------------------------- ### Example: Add a single tag (YAML) Source: https://organize.readthedocs.io/en/latest/actions This YAML configuration demonstrates how to add a single tag named 'Invoice' to files that start with 'Invoice' and have a '.pdf' extension within the '~/Documents/Invoices' directory. ```yaml rules: - name: "add a single tag" locations: "~/Documents/Invoices" filters: - name: startswith: "Invoice" - extension: pdf actions: - macos_tags: Invoice ``` -------------------------------- ### Example: Show File Hashes and Sizes (YAML) Source: https://organize.readthedocs.io/en/latest/filters This example demonstrates how to use the 'hash' and 'size' filters within a YAML configuration. It defines a rule to process files in a specified location, applies both filters, and then echoes the calculated hash and decimal size of each file. ```yaml rules: - name: "Show the hashes and size of your files" locations: "~/Desktop" filters: - hash - size actions: - echo: "{hash} {size.decimal}" ``` -------------------------------- ### Build and Test Organize Docker Image Source: https://organize.readthedocs.io/en/latest/docker Commands to build the Docker image from the Dockerfile and verify the installation by displaying the help text. ```bash docker build -t organize . docker run organize ``` -------------------------------- ### Configure Organize Docker Run Source: https://organize.readthedocs.io/en/latest/docker Example configuration file and command to run the container while mounting local directories and configuration files. ```yaml rules: - locations: /data actions: - echo: "Found file: {path}" ``` ```bash docker run -v ./docker-conf.yml:/config/config.yml -v .:/data organize run ``` -------------------------------- ### Install organize tool via pip Source: https://organize.readthedocs.io/en/latest Installs or updates the organize-tool package using the Python package manager. Requires Python 3.9 or higher. ```bash pip install -U organize-tool ``` -------------------------------- ### Convert All File Extensions to Lowercase Example in YAML Source: https://organize.readthedocs.io/en/latest/actions This YAML example shows how to use the rename action to convert all file extensions to lowercase. It applies to any file with an extension and uses a template to construct the new filename with the lowercase version of the original extension. ```yaml rules: - name: "Convert **all** file extensions to lowercase" locations: "~/Desktop" filters: - name - extension actions: - rename: "{name}.{extension.lower()}" ``` -------------------------------- ### Write Action Configuration Example (YAML) Source: https://organize.readthedocs.io/en/latest/actions This YAML configuration demonstrates how to use the 'write' action within a rule. It specifies the output file, the text content with templating, the write mode, and enables clearing the file before the first write. ```yaml rules: - name: "Record file sizes" locations: ~/Downloads filters: - size actions: - write: outfile: "./sizes.txt" text: "{size.traditional} -- {relative_path}" mode: "append" clear_before_first_write: true ``` -------------------------------- ### Match files starting with 'Invoice' (YAML) Source: https://organize.readthedocs.io/en/latest/filters An example rule in YAML format that uses the 'name' filter to match all files starting with the string 'Invoice'. It specifies the location to scan and the action to perform on matched files. ```yaml rules: - locations: "~/Desktop" filters: - name: startswith: Invoice actions: - echo: "This is an invoice" ``` -------------------------------- ### Example: Add multiple tags (YAML) Source: https://organize.readthedocs.io/en/latest/actions This YAML configuration shows how to add multiple tags, 'Important' and 'Invoice', to files matching the specified filters within the '~/Documents/Invoices' directory. ```yaml rules: - locations: "~/Documents/Invoices" filters: - name: startswith: "Invoice" - extension: pdf actions: - macos_tags: - Important - Invoice ``` -------------------------------- ### Rename File Extension Example in YAML Source: https://organize.readthedocs.io/en/latest/actions This example demonstrates how to use the rename action in a YAML configuration to change file extensions. It targets files with the '.PDF' extension and renames them to have a '.pdf' extension, effectively converting them to lowercase. ```yaml rules: - name: "Convert all .PDF file extensions to lowercase (.pdf)" locations: "~/Desktop" filters: - name - extension: PDF actions: - rename: "{name}.pdf" ``` -------------------------------- ### Example: Add a templated tag with color (YAML) Source: https://organize.readthedocs.io/en/latest/actions This YAML example demonstrates adding a templated tag 'Year-{created.year}' with a 'red' color. The tag dynamically includes the file's creation year, applied to files matching the 'created' filter. ```yaml rules: - locations: "~/Documents/Invoices" filters: - created actions: - macos_tags: - "Year-{created.year} (red)" ``` -------------------------------- ### Define organize configuration rules Source: https://organize.readthedocs.io/en/latest Examples of YAML configuration rules for the organize tool. These snippets demonstrate how to filter files by extension, content, or directory status and perform actions like moving or deleting files. ```yaml rules: - name: "Find PDFs" locations: - ~/Downloads subfolders: true filters: - extension: pdf actions: - echo: "Found PDF!" ``` ```yaml actions: - echo: "Found PDF!" - move: ~/Documents/PDFs/ ``` ```yaml rules: - name: "Sort my invoices and receipts" locations: ~/Downloads subfolders: true filters: - extension: pdf - name: contains: - Invoice - Order - Purchase case_sensitive: false actions: - move: ~/Documents/Shopping/ ``` ```yaml rules: - name: "Recursively delete all empty directories" locations: - path: ~/Downloads targets: dirs subfolders: true filters: - empty actions: - delete ``` -------------------------------- ### Configure Confirm Action in YAML Source: https://organize.readthedocs.io/en/latest/actions Example configuration demonstrating how to use the 'confirm' action within an Organize rule set to prompt the user before moving files to the trash. ```yaml rules: - name: "Delete duplicates with confirmation" locations: - ~/Downloads - ~/Documents filters: - not empty - duplicate - name actions: - confirm: "Delete {name}?" - trash ``` -------------------------------- ### Example Usage of date_lastused Filter (YAML) Source: https://organize.readthedocs.io/en/latest/filters Demonstrates how to use the date_lastused filter in a configuration file to display the last used date of files. This example assumes a 'rules' structure and an 'echo' action. ```yaml rules: - name: Show the date the file was added to the folder locations: "~/Desktop" filters: - date_lastused actions: - echo: "Date last used: {date_lastused.strftime('%Y-%m-%d')}" ``` -------------------------------- ### Example: Show Content of PDF Files using organize Source: https://organize.readthedocs.io/en/latest/filters This example demonstrates how to use the filecontent filter within the organize framework to display the content of all PDF files in a specified location. It utilizes the 'echo' action to print the matched content. ```yaml rules: - name: "Show the content of all your PDF files" locations: ~/Documents filters: - extension: pdf - filecontent actions: - echo: "{filecontent}" ``` -------------------------------- ### Example: Specify tag colors (YAML) Source: https://organize.readthedocs.io/en/latest/actions This YAML configuration illustrates how to assign specific colors ('green' for 'Important', 'purple' for 'Invoice') to multiple tags applied to files matching the defined criteria. ```yaml rules: - locations: "~/Documents/Invoices" filters: - name: startswith: "Invoice" - extension: pdf actions: - macos_tags: - Important (green) - Invoice (purple) ``` -------------------------------- ### Organize Aliases for Multiple Locations (YAML) Source: https://organize.readthedocs.io/en/latest/rules Demonstrates the use of YAML anchors and aliases to define and reuse lists of locations in organize rules. This example defines 'all_my_messy_folders' and references it using '*all' in multiple rules for conciseness. ```yaml all_my_messy_folders: &all - ~/Desktop - ~/Downloads - ~/Documents - ~/Dropbox rules: - locations: *all filters: ... actions: ... - locations: *all filters: ... actions: ... ``` -------------------------------- ### Example: Filter Filename by Date Code using organize Regex Source: https://organize.readthedocs.io/en/latest/filters This example illustrates filtering files based on a date code pattern in their filenames using the regex filter. It demonstrates how to capture year, month, and day using named groups and display the extracted year. ```yaml rules: - locations: ~/Desktop filters: - regex: '(?P20\d{2})-[01]\d-[0123]\d.*' actions: - echo: "Year: {regex.year}" ``` -------------------------------- ### Move Action Configuration in YAML Source: https://organize.readthedocs.io/en/latest/actions Example usage of the move action within an organize configuration file, demonstrating how to move files into specific directories based on extensions. ```yaml rules: - locations: ~/Desktop filters: - extension: - pdf - jpg actions: - move: "~/Desktop/media/" ``` -------------------------------- ### Regex Filter Usage Example (YAML) Source: https://organize.readthedocs.io/en/latest/filters This YAML configuration demonstrates how to use the Regex filter to move PDF invoice files from the Desktop to a specific directory. It shows a basic match and a more advanced example using named groups. ```yaml rules: - locations: "~/Desktop" filters: - regex: '^RG(\d{12})-sig\.pdf$' actions: - move: "~/Documents/Invoices/1und1/" rules: - locations: ~/Desktop filters: - regex: '^RG(?P\d{12})-sig\.pdf$' actions: - move: ~/Documents/Invoices/1und1/{regex.the_number}.pdf ``` -------------------------------- ### Example: Match Invoice and Sort by Customer using organize Source: https://organize.readthedocs.io/en/latest/filters This example shows how to use the filecontent filter with a regular expression to extract customer information from invoice files. The extracted customer name is then used to organize the files into specific directories. ```yaml rules: - name: "Match an invoice with a regular expression and sort by customer" locations: "~/Desktop" filters: - filecontent: 'Invoice.*Customer (?P\w+)' actions: - move: "~/Documents/Invoices/{filecontent.customer}/" ``` -------------------------------- ### Example Usage of date_added Filter (YAML) Source: https://organize.readthedocs.io/en/latest/filters This example demonstrates how to use the `date_added` filter within an Organize rules file. It shows how to specify the location to monitor and apply the filter to echo the date the file was added to the folder. ```yaml rules: - name: Show the date the file was added to the folder locations: "~/Desktop" filters: - date_added actions: - echo: "Date added: {date_added.strftime('%Y-%m-%d')}" ``` -------------------------------- ### Organize Placeholder Usage with Filters (YAML) Source: https://organize.readthedocs.io/en/latest/rules An example of using placeholders within the 'echo' action in an organize configuration. This rule utilizes 'size' and 'hash' filters, making their returned values available as placeholders '{size}' and '{hash}' in the action. ```yaml rules: - locations: ~/Desktop filters: - size - hash actions: - echo: "{size} {hash}" ``` -------------------------------- ### Define Organize Rules in YAML Source: https://organize.readthedocs.io/en/latest/actions Example configuration showing how to use the trash action within an organize rule to clean up old files based on extension and modification date. ```yaml rules: - name: Move all JPGs and PNGs on the desktop which are older than one year into the trash locations: "~/Desktop" filters: - lastmodified: years: 1 mode: older - extension: - png - jpg actions: - trash ``` -------------------------------- ### Configure Shell Action in YAML Source: https://organize.readthedocs.io/en/latest/actions Example configuration for the shell action within an Organize rule file. This snippet demonstrates how to use the shell action to open PDF files located on the desktop. ```yaml rules: - name: "On macOS: Open all pdfs on your desktop" locations: "~/Desktop" filters: - extension: pdf actions: - shell: 'open "{path}"' ``` -------------------------------- ### Define Organize Rules for EXIF Data Source: https://organize.readthedocs.io/en/latest/filters YAML configuration examples for using the EXIF filter. These snippets demonstrate how to echo metadata to the console or filter files based on specific GPS tags. ```yaml rules: - name: "Show available EXIF data of your pictures" locations: - path: ~/Pictures max_depth: null filters: - exif actions: - echo: "{exif}" - name: "GPS demo" locations: - path: ~/Pictures max_depth: null filters: - exif: gps.gpsdate ``` -------------------------------- ### Organize Rule Options (YAML Structure) Source: https://organize.readthedocs.io/en/latest/rules An example YAML structure illustrating the various options available for defining a single rule in the organize configuration. This includes name, enabled status, targets, locations, subfolders, filter mode, filters, actions, and tags. ```yaml rules: # First rule - name: ... enabled: ... targets: ... locations: ... subfolders: ... filter_mode: ... filters: ... actions: ... tags: ... # Another rule - name: ... enabled: ... # ... and so on ``` -------------------------------- ### Filter files by extension using YAML Source: https://organize.readthedocs.io/en/latest/filters Examples of using the extension filter in YAML rules to match specific file types, handle multiple extensions, and perform string manipulation on filenames. ```yaml rules: - name: "Match a single file extension" locations: "~/Desktop" filters: - extension: png actions: - echo: "Found PNG file: {path}" - name: "Match multiple file extensions" locations: "~/Desktop" filters: - extension: - .jpg - jpeg actions: - echo: "Found JPG file: {path}" - name: "Make all file extensions lowercase" locations: "~/Desktop" filters: - extension actions: - rename: "{path.stem}.{extension.lower()}" - name: "Using extension lists" locations: "~/Desktop" filters: - extension: - *img - *audio actions: - echo: "Found media file: {path}" ``` -------------------------------- ### Open Google Search with Python Script Source: https://organize.readthedocs.io/en/latest/actions Uses a Python script action to open a web browser and perform a Google search based on a filename that starts with an underscore. This illustrates using external libraries and dynamic URL generation. ```python rules: - locations: ~/Desktop filters: - name: startswith: "_" actions: - python: | import webbrowser webbrowser.open('https://www.google.com/search?q=%s' % name) ``` -------------------------------- ### Match files starting with 'A', containing 'hole', case-insensitive (YAML) Source: https://organize.readthedocs.io/en/latest/filters A YAML rule demonstrating case-insensitive matching for files that start with 'A' and contain the string 'hole'. This example highlights the use of the 'case_sensitive' attribute set to false. ```yaml rules: - locations: "~/Desktop" filters: - name: startswith: A contains: hole case_sensitive: false actions: - echo: "Found a match." ``` -------------------------------- ### Update Jinja placeholders for date formatting Source: https://organize.readthedocs.io/en/latest/migrating Demonstrates the transition from legacy placeholder syntax to Jinja-based strftime formatting for date objects. ```text "{created.year}-{created.month:02}-{created.day:02}" ``` ```jinja "{created.strftime('%Y-%m-%d')}" ``` -------------------------------- ### Execute organize commands Source: https://organize.readthedocs.io/en/latest Commands to run the organize tool, including executing rules and simulating actions to preview changes before they are applied. ```bash organize run ``` ```bash organize sim ``` -------------------------------- ### Organize Advanced Aliases for Folder Lists (YAML) Source: https://organize.readthedocs.io/en/latest/rules No description ```yaml private_folders: &private - "/path/private" - "~/path/private" work_folders: &work - "/path/work" - "~/My work folder" all_folders: &all - *private - *work rules: - locations: *private filters: ... actions: ... - locations: *work filters: ... actions: ... - locations: *all filters: ... actions: ... # same as *all - locations: - *work - *private filters: ... actions: ... ``` -------------------------------- ### Create and Run a Basic PDF Sorting Rule Source: https://organize.readthedocs.io/en/latest?badge=latest Demonstrates creating a simple rule to identify PDF files in the Downloads folder and echo a message. It then shows how to move these PDFs to a 'Documents/PDFs' folder and simulate the action before running it. ```yaml rules: - name: "Find PDFs" locations: - ~/Downloads subfolders: true filters: - extension: pdf actions: - echo: "Found PDF!" ``` ```yaml actions: - echo: "Found PDF!" - move: ~/Documents/PDFs/ ``` -------------------------------- ### Pass Configuration via Stdin Source: https://organize.readthedocs.io/en/latest/docker Command to execute the organize container by piping the configuration file directly into stdin, avoiding the need for volume mounts for the config file. ```bash docker run -i organize check --stdin < ./docker-conf.yml ``` -------------------------------- ### Minimal Organize Configuration (YAML) Source: https://organize.readthedocs.io/en/latest/rules A basic organize configuration file in YAML format. It defines a single rule with a location and a simple 'echo' action. This configuration will print 'Hello World!' for each file found in the specified location. ```yaml rules: - locations: "~/Desktop" actions: - echo: "Hello World!" ``` -------------------------------- ### Apply Created Filter in Rules Source: https://organize.readthedocs.io/en/latest/filters Examples of using the 'created' filter to match files based on age, sort them into directories, or format their creation date strings. ```yaml rules: - name: Show all files on your desktop created at least 10 days ago locations: "~/Desktop" filters: - created: days: 10 actions: - echo: "Was created at least 10 days ago" - name: Show all files on your desktop which were created within the last 5 hours locations: "~/Desktop" filters: - created: hours: 5 mode: newer actions: - echo: "Was created within the last 5 hours" - name: Sort pdfs by year of creation locations: "~/Documents" filters: - extension: pdf - created actions: - move: "~/Documents/PDF/{created.year}/" - name: Display the creation date locations: "~/Documents" filters: - extension: pdf - created actions: - echo: "ISO Format: {created.strftime('%Y-%m-%d')}" - echo: "As timestamp: {created.timestamp() | int}" ``` -------------------------------- ### Migrate move action configuration Source: https://organize.readthedocs.io/en/latest/migrating Illustrates the transition from legacy move action arguments to the v2 conflict resolution syntax. ```yaml rules: - folders: ~/Desktop filters: - extension: pdf actions: - move: dest: ~/Documents/PDFs/ overwrite: false counter_seperator: "-" ``` ```yaml rules: - locations: ~/Desktop filters: - extension: pdf actions: - move: dest: ~/Documents/PDFs/ on_conflict: rename_new rename_template: "{name}-{counter}{extension}" ``` -------------------------------- ### Recursively Delete Empty Directories Source: https://organize.readthedocs.io/en/latest?badge=latest A rule to recursively find and delete all empty directories within the specified locations, starting from the Downloads folder. ```yaml rules: - name: "Recursively delete all empty directories" locations: - path: ~/Downloads targets: dirs subfolders: true filters: - empty actions: - delete ``` -------------------------------- ### Define File Size and Extension Rules Source: https://organize.readthedocs.io/en/latest/actions This snippet defines a rule for organizing files based on their size and extension. It specifies the location, filters to apply, and actions to perform, such as writing file information to an output file. The `outfile` parameter uses templates to dynamically create filenames based on file extensions, and the `text` parameter formats the output content with file size and relative path. ```yaml rules: - name: "File sizes by extension" locations: ~/Downloads filters: - size - extension actions: - write: outfile: "./sizes.{extension}.txt" text: "{size.traditional} -- {relative_path}" mode: "prepend" clear_before_first_write: true ``` -------------------------------- ### Configure system file inclusion Source: https://organize.readthedocs.io/en/latest/migrating Demonstrates how to override default system exclusion settings to include hidden files like .DS_Store in v2. ```yaml rules: - locations: - path: ~/Desktop/ system_exclude_files: [] system_exclude_dirs: [] filters: - name: .DS_Store actions: - trash ``` -------------------------------- ### Full Location Options Configuration Source: https://organize.readthedocs.io/en/latest/locations Demonstrates the comprehensive set of options available for configuring a location, including depth controls, search strategies, file/directory exclusion patterns, error handling, and filtering. ```yaml rules: - locations: - path: ... min_depth: ... max_depth: ... search: ... exclude_files: ... exclude_dirs: ... system_exclude_files: ... system_exclude_dirs: ... ignore_errors: ... filter: ... filter_dirs: ... ``` -------------------------------- ### Apply numeric padding in Jinja templates Source: https://organize.readthedocs.io/en/latest/migrating Shows how to perform zero-padding on variables using Python-style formatting within Jinja templates. ```jinja "{'%02d' % your_variable}" # or "{ '{:02}'.format(your_variable) }" ``` -------------------------------- ### Use Environment Variables in Location Paths Source: https://organize.readthedocs.io/en/latest/locations Shows how to dynamically set location paths using environment variables, either via the `{env}` placeholder or a dollar sign prefix. This enhances flexibility by allowing paths to be defined outside the configuration file. ```yaml rules: - locations: # via {env} - the "" are important here! - "{env.MY_FOLDER}" # via $ - equal to the one above. - "$MY_FOLDER" # with location options - path: "{env.OTHER_FOLDER}/Inbox/Invoices" max_depth: null actions: - echo: "{path}" ``` -------------------------------- ### Configure LastModified filter in YAML rules Source: https://organize.readthedocs.io/en/latest/filters Examples of how to use the lastmodified filter within organize YAML rule files. Demonstrates filtering by days, hours, and using the filter output for file organization and formatting. ```yaml rules: - name: "Show all files on your desktop last modified at least 10 days ago" locations: "~/Desktop" filters: - lastmodified: days: 10 actions: - echo: "Was modified at least 10 days ago" - locations: "~/Desktop" filters: - lastmodified: hours: 5 mode: newer actions: - echo: "Was modified within the last 5 hours" - name: "Sort pdfs by year of last modification" locations: "~/Documents" filters: - extension: pdf - lastmodified actions: - move: "~/Documents/PDF/{lastmodified.year}/" - name: Formatting the lastmodified date locations: "~/Documents" filters: - extension: pdf - lastmodified actions: - echo: "ISO Format: {lastmodified.strftime('%Y-%m-%d')}" - echo: "As timestamp: {lastmodified.timestamp() | int}" ``` -------------------------------- ### Organize files by camera manufacturer using YAML Source: https://organize.readthedocs.io/en/latest/filters Demonstrates how to use EXIF data to filter and move files into directories based on the camera model. This allows for automated categorization of image libraries. ```yaml rules: - name: "Filter by camera manufacturer" locations: - path: ~/Pictures max_depth: null filters: - exif: image.model: Nikon D3200 actions: - move: "~/Pictures/My old Nikon/" - name: "camera sort" locations: - path: ~/Pictures max_depth: null filters: - extension: jpg - exif: image.model actions: - move: "~/Pictures/{exif.image.model}/" ``` -------------------------------- ### Trash Files and Directories with Python Source: https://organize.readthedocs.io/en/latest/actions The Trash class provides a simple interface to move files or directories into the system trash. It integrates into the pipeline to safely handle resource removal. ```python @dataclass(config=ConfigDict(coerce_numbers_to_str=True, extra="forbid")) class Trash: def pipeline(self, res: Resource, output: Output, simulate: bool): assert res.path is not None, "Does not support standalone mode" output.msg(res=res, msg=f'Trash "{res.path}"', sender=self) if not simulate: trash(res.path) ``` -------------------------------- ### Echo Message with Placeholder Variables Source: https://organize.readthedocs.io/en/latest/actions Prints a specified message to the output. This action is useful for testing rules and can incorporate placeholder variables like {path} or {extension.upper()} to display dynamic information about files. ```yaml rules: - name: "Find files older than a year" locations: ~/Desktop filters: - lastmodified: days: 365 actions: - echo: "Found old file" ``` ```yaml rules: - locations: - ~/Desktop actions: - echo: "Hello World! {path}" ``` ```yaml rules: - locations: - ~/Desktop filters: - extension - name actions: - echo: 'Found a {extension.upper()}: "{name}"' ``` ```yaml rules: - locations: - path: ~/Desktop max_depth: null - path: ~/Downloads max_depth: null actions: - echo: "Path: {path}" - echo: "Relative: {relative_path}" ``` -------------------------------- ### Configure EXIF Tool Path Source: https://organize.readthedocs.io/en/latest/filters Sets the environment variable to point to the exiftool executable, allowing the organize library to use it for metadata extraction if the default exifread library is insufficient. ```shell ORGANIZE_EXIFTOOL_PATH="exiftool" ``` -------------------------------- ### Check Duplicates Between Desktop and Zip, Select Original by Creation Date (YAML Configuration) Source: https://organize.readthedocs.io/en/latest/filters This YAML configuration demonstrates how to check for duplicate files between a local directory (Desktop) and a zip archive. It specifies 'created' as the method for detecting the original file among duplicates. The 'echo' action is used to notify when a duplicate is found. ```yaml rules: - name: "Check for duplicated files between Desktop and a Zip file, select original by creation date" locations: - ~/Desktop - zip://~/Desktop/backup.zip filters: - duplicate: detect_original_by: "created" actions: - echo: "Duplicate found!" ``` -------------------------------- ### Run Python Scripts in Simulation Mode Source: https://organize.readthedocs.io/en/latest/actions Shows how to execute a Python script action in simulation mode, preventing actual file modifications while still logging the intended actions. This is useful for testing and verifying script behavior. ```yaml my_python_script: &script | print("Hello World!") print(path) rules: - name: "Run in simulation and yaml alias" locations: - ~/Desktop/ actions: - python: code: *script run_in_simulation: yes ``` -------------------------------- ### Write Text to File (Python) Source: https://organize.readthedocs.io/en/latest/actions This Python class implements the 'write' action, allowing text to be written to a specified file. It handles file creation, different write modes (append, prepend, overwrite), encoding, and optional newline characters. The `clear_before_first_write` attribute ensures the file is cleared only on the initial write operation. ```python from dataclasses import dataclass, field from pathlib import Path from typing import Literal, ClassVar from organize.config import ConfigDict from organize.resource import Resource from organize.output import Output from organize.template import Template, render @dataclass(config=ConfigDict(coerce_numbers_to_str=True, extra="forbid")) class Write: """ Write text to a file. If the specified path does not exist it will be created. Attributes: text (str): The text that should be written. Supports templates. outfile (str): The file `text` should be written into. Supports templates. mode (str): Can be either `append` (append text to the file), `prepend` (insert text as first line) or `overwrite` (overwrite content with text). Defaults to `append`. encoding (str): The text encoding to use. Default: "utf-8". newline (str): (Optional) Whether to append a newline to the given `text`. Defaults to `true`. clear_before_first_write (bool): (Optional) Clears the file before first appending / prepending text to it. This happens only the first time the file is written to. If the rule filters don't match anything the file is left as it is. Defaults to `false`. """ text: str outfile: str mode: Literal["append", "prepend", "overwrite"] = "append" encoding: str = "utf-8" newline: bool = True clear_before_first_write: bool = False action_config: ClassVar[ActionConfig] = ActionConfig( name="write", standalone=True, files=True, dirs=True, ) def __post_init__(self): self._text = Template.from_string(self.text) self._path = Template.from_string(self.outfile) self._known_files = set() def pipeline(self, res: Resource, output: Output, simulate: bool): text = render(self._text, res.dict()) path = Path(render(self._path, res.dict())) resolved = path.resolve() if resolved not in self._known_files: self._known_files.add(resolved) if not simulate: resolved.parent.mkdir(parents=True, exist_ok=True) # clear on first write if resolved.exists() and self.clear_before_first_write: output.msg(res=res, msg=f"Clearing file {path}", sender=self) if not simulate: resolved.open("w") # clear the file output.msg(res=res, msg=f'{path}: {self.mode} "{text}"", sender=self) if self.newline: text += "\n" if not simulate: if self.mode == "append": with open(path, "a", encoding=self.encoding) as f: f.write(text) elif self.mode == "prepend": content = "" if path.exists(): content = path.read_text(encoding=self.encoding) path.write_text(text + content, encoding=self.encoding) elif self.mode == "overwrite": path.write_text(text, encoding=self.encoding) ``` -------------------------------- ### Copy Files with Extension Filtering and Overwriting Source: https://organize.readthedocs.io/en/latest/actions Copies all .pdf and .jpg files from a source folder to a destination folder, overwriting existing files. It categorizes files into 'PDF' and 'JPG' subfolders based on their extension. ```yaml rules: - locations: "~/Desktop/somefolder/" filters: - extension: - pdf - jpg actions: - copy: dest: "~/Desktop/{extension.upper()}/" on_conflict: overwrite ```