A file extension is the suffix after the final dot in a filename, conventionally indicating its file type. With pathlib, Path.suffix returns that dotted suffix, while Path.stem returns the filename without it. section 12.2.5
File extensions support routine filesystem tasks:
- Match files by pattern, such as *.txt or filenames ending in .test. section 12.6 section 20.2
- Rename files by modifying the stem while preserving and reattaching the suffix. section 20.2
- Use Path objects to access suffixes without special string parsing. section 20.2
Adding a date without losing the extension
For item_info.txt, pathlib exposes stem as item_info and suffix as .txt. Combining them as item_info_2024-09-15.txt preserves the file type while creating a dated archive filename. section 20.2
Listing 20.1 File files_01.py
import datetime
import pathlib
FILE_PATTERN = "*.txt" #1
ARCHIVE = "archive"
def main():
date_string = datetime.date.today().strftime("%Y-%m-%d") #2
cur_path = pathlib.Path(".")
archive_path = cur_path.joinpath(ARCHIVE)
archive_path.mkdir(exist_ok=True) #3
paths = cur_path.glob(FILE_PATTERN)
for path in paths:
new_filename = f"{path.stem}_{date_string}{path.suffix}"
new_path = archive_path.joinpath(
new_filename) #4
path.rename(new_path) #5
if __name__ == '__main__':
main()
The listing demonstrates matching .txt files, combining path.stem with path.suffix, and moving renamed files into an archive directory. section 20.2
