antsibull-fileutils

1.5.2 · active · verified Thu Apr 16

antsibull-fileutils is a Python library providing file utility functions primarily used by other community Ansible tools. It's an integral part of the broader antsibull ecosystem, which assists in building the Ansible Distribution. The library follows semantic versioning from version 1.0.0 onwards, aiming to avoid backward-incompatible changes within a major release cycle, though exceptions may occur for critical security fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `write_file` to write content to a file and `ansible_mkdtemp` or `AnsibleTemporaryDirectory` to create and manage temporary directories, which are common file operations provided by the library. Note that `write_file` expects bytes for content.

from antsibull_fileutils.io import write_file
from antsibull_fileutils.tempfile import ansible_mkdtemp, AnsibleTemporaryDirectory
import os

# Example 1: Writing to a file
try:
    temp_dir = ansible_mkdtemp()
    file_path = os.path.join(temp_dir, "test_file.txt")
    content = "Hello, antsibull-fileutils!"
    write_file(file_path, content.encode('utf-8'))
    with open(file_path, 'r') as f:
        read_content = f.read()
    print(f"Successfully wrote and read: {read_content}")
except Exception as e:
    print(f"Error: {e}")
finally:
    # In a real application, you'd clean up the temp_dir
    print(f"Temporary directory created at: {temp_dir}")

# Example 2: Using AnsibleTemporaryDirectory context manager
with AnsibleTemporaryDirectory() as temp_dir_obj:
    print(f"Temporary directory (context manager): {temp_dir_obj.name}")
    another_file_path = os.path.join(temp_dir_obj.name, "another_file.txt")
    write_file(another_file_path, b"Context manager test")
    assert os.path.exists(another_file_path)
print("Temporary directory from context manager cleaned up automatically.")

view raw JSON →