Skip to content

Handlers#

BasicHandler #

Basic file name manipulation.

Parameters:

Name Type Description Default
method str

Specify how to modify the file name. Accepted values are (add_prefix, add_suffix, remove_prefix, remove_suffix).

required
value str

Value to add or remove from the file name.

required
Source code in renameit/handlers/basic.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class BasicHandler(IHandler):
    """Basic file name manipulation.

    Args:
        method (str): Specify how to modify the file name. Accepted values are
            (`add_prefix, add_suffix, remove_prefix, remove_suffix`).
        value (str): Value to add or remove from the file name.
    """

    name = "basic"

    def __init__(self, method: str, value: str):

        super().__init__()

        if method not in ["add_prefix", "add_suffix", "remove_prefix", "remove_suffix"]:
            raise ValueError(f"method: '{method}' is not supported.")

        self.method = method
        self.value = value

    def get_new_name(self, file_obj: FileObject) -> FileObject:
        path = pathlib.Path(file_obj.path)
        return FileObject(
            path=str(
                {
                    "add_prefix": path.with_name(self.value + path.name),
                    "add_suffix": path.with_name(path.stem + self.value + path.suffix),
                    "remove_prefix": path.with_name(path.name.removeprefix(self.value)),
                    "remove_suffix": path.with_name(
                        path.stem.removesuffix(self.value) + path.suffix
                    ),
                }[self.method]
            ),
            modified_date=file_obj.modified_date,
        )

DateTimeHandler #

Add datetime values to file names.

Parameters:

Name Type Description Default
dt_value str

Specify where to get date & time values from:

  • modification_date uses the file's latest modification datetime
  • now uses the current utc datetime
required
dt_format str

How to format the dt_value when placing it in the file name. Refer to https://strftime.org/ for more info about accepted format directives.

required
add_as str

Where to add dt_value in the file name. Either "prefix" or "suffix".

required
Source code in renameit/handlers/datetime.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class DateTimeHandler(IHandler):
    """Add datetime values to file names.

    Args:
        dt_value (str): Specify where to get date & time values from:

            - `modification_date` uses the file's latest modification datetime
            - `now` uses the current utc datetime

        dt_format (str): How to format the `dt_value` when placing it in the file name.
            Refer to https://strftime.org/ for more info about accepted format directives.
        add_as (str): Where to add `dt_value` in the file name.
            Either "prefix" or "suffix".
    """

    name = "datetime"

    def __init__(self, dt_value: str, dt_format: str, add_as: str):

        super().__init__()

        if dt_value not in ["modification_date", "now"]:
            raise ValueError(
                f"Wrong value `{dt_value}` provided in `dt_value`, "
                + "should be either `now` or `modification_date`."
            )

        if add_as not in ["prefix", "suffix"]:
            raise ValueError(
                f"Wrong value `{add_as}` provided in `add_as`, "
                + "should be either `prefix` or `suffix`."
            )

        self.dt: Optional[datetime] = datetime.utcnow()
        self.dt_value = dt_value
        self.dt_format = dt_format
        self.add_as = add_as

    def get_new_name(self, file_obj: FileObject) -> FileObject:
        path = pathlib.Path(file_obj.path)

        if self.dt_value == "modification_date":
            self.dt = file_obj.modified_date

        if self.dt is not None:
            return FileObject(
                path=str(
                    {
                        "prefix": path.with_name(self.dt.strftime(self.dt_format) + path.name),
                        "suffix": path.with_name(
                            path.stem + self.dt.strftime(self.dt_format) + path.suffix
                        ),
                    }[self.add_as]
                ),
                modified_date=file_obj.modified_date,
            )
        else:
            return file_obj

RegexHandler #

Manipulate file paths using regular expressions.

It works by using matching pattern with named groups and then using those groups into a replacement string template passed on to the re.sub method.

Example:

match_pattern = r"(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/(?P<file_name>.*)".
replace_pattern = "year=\g<year>/month=\g<month>/day=\g<day>/\g<file_name>".
transforms "2022/01/01/file1.csv" to "year=2022/month=01/day=01/file1.csv".

Parameters:

Name Type Description Default
match_pattern str

Regular expressiong with named capturing groups.

required
replace_pattern str

String that contains the named replacement syntax for the caught named groups if there is a match.

required
case_sensitive bool

Applies case sensitive matching. Defaults to True.

True
Source code in renameit/handlers/regex.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class RegexHandler(IHandler):
    """Manipulate file paths using regular expressions.

    It works by using matching pattern with named groups and then using those groups
    into a replacement string template passed on to the re.sub method.

    Example:
    ```
    match_pattern = r"(?P<year>\\d+)/(?P<month>\\d+)/(?P<day>\\d+)/(?P<file_name>.*)".
    replace_pattern = "year=\\g<year>/month=\\g<month>/day=\\g<day>/\\g<file_name>".
    transforms "2022/01/01/file1.csv" to "year=2022/month=01/day=01/file1.csv".
    ```

    Args:
        match_pattern (str): Regular expressiong with named capturing groups.
        replace_pattern (str): String that contains the named replacement syntax for the
                            caught named groups if there is a match.
        case_sensitive (bool, optional): Applies case sensitive matching. Defaults to True.
    """

    name = "regex"

    def __init__(self, match_pattern: str, replace_pattern: str, case_sensitive: bool = True):

        super().__init__()

        self.match_pattern = match_pattern
        self.replace_pattern = replace_pattern
        self.case_sensitive = case_sensitive

        if case_sensitive:
            self.match_pattern_compiled = re.compile(match_pattern, re.IGNORECASE)
        else:
            self.match_pattern_compiled = re.compile(match_pattern)

    def get_new_name(self, file_obj: FileObject) -> FileObject:
        return FileObject(
            path=self.match_pattern_compiled.sub(self.replace_pattern, file_obj.path),
            modified_date=file_obj.modified_date,
        )