File Utilities
Learn how to work with files and directories using the file_utils module.
The file_utils module provides a set of helper functions to simplify common file and directory operations within your plugin, such as accessing standard Telegram directories, reading/writing files, and listing directory contents.
Standard Directories
These functions return the absolute paths to various standard directories used by Telegram, making it easy to store and retrieve files in the correct locations.
Directory Operations
ensure_dir_exists
Ensures that a directory exists. If it doesn't, it will be created, including any necessary parent directories.
list_dir
Lists the contents of a directory with options for recursion, filtering by type (files/dirs), and file extension.
Parameters:
recursive=False: walk child directories tooinclude_files=True: include files in the resultinclude_dirs=False: include directories in the resultextensions=None: optional suffix filter such as[".json", ".txt"]
File Operations
These functions provide simple wrappers for reading, writing, and deleting files.
write_file
Writes a string to a file, overwriting it if it already exists.
write_file(...) does not create parent directories for you, so pair it with ensure_dir_exists(...) when needed.
read_file
Reads the entire content of a file into a string.
On failure, read_file(...) returns None and logs the exception.
delete_file
Deletes a file from the filesystem.
delete_file(...) returns:
Truewhen the file was deletedFalsewhen deletion failed or the file did not exist