liveBook · Manning

File extension

As explained in The Quick Python Book, Fourth Edition

A file extension is a suffix in a filename, commonly separated by a dot, that conventionally indicates a file type.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains suffix and stem access through pathlib, then applies them to matching and renaming; it stops short of filesystem implementation details.
Examples
Uses .txt and .test files, dated archive names, glob patterns, and a pathlib script that moves renamed files.
What you can do after
Operate pathlib to identify extensions, preserve them during renaming, match file patterns, and move files into an archive.
How it connects
Connects file extensions with pathlib, wildcard matching, file renaming, archiving, and filesystem operations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.