liveBook · Manning

File path

As explained in Python How-To

A file path is a textual or structured identifier specifying the location of a file or directory in a filesystem.

A file path identifies a file or directory. In Python, pathlib’s Path class provides path operations; combining a directory and filename with `/` creates a path that works across operating systems. section 11.4.1 section 11.6

Use Path objects to manage files and inspect their names:

  • Create directories with mkdir and check paths with exists. section 11.4.1
  • Find matching files with glob; create target paths and move files with rename, or remove files with unlink. section 11.4.3 section 11.4.5
  • Read path details through parent, name, stem, and suffix. section 11.5.1
Listing 11.18 Retrieving filename information
from pathlib import Path
 
subjects_folder = Path("subjects")
 
for dat_path in subjects_folder.glob("**/*.dat"):                       #1
 
    subject_dir = dat_path.parent                                       #2
 
    filename = dat_path.stem                                            #3
 
    config_path = subject_dir / f"{filename}.config"
 
    print(f"{subject_dir} & {filename} -> {config_path}")
 
    dat_exists = dat_path.exists()
    config_exists = config_path.exists()
 
    with open(dat_path) as dat_file, open(config_path) as config_file:  #4
        print(f"Process {filename}: dat? {dat_exists}, config? 
 {config_exists}\n")
        # process the subject's data
 
# output the following lines:
subjects/subject_125 & subject_125 -> subjects/subject_125/subject_125.config
Process subject_125: dat? True, config? True
 
subjects/subject_124 & subject_124 -> subjects/subject_124/subject_124.config
Process subject_124: dat? True, config? True
 
subjects/subject_123 & subject_123 -> subjects/subject_123/subject_123.config
Process subject_123: dat? True, config? True

Follow a pattern that finds .dat files in subject folders, retrieves each file’s directory and stem, and constructs the matching .config path. section 11.5.1

How Python How-To covers it

How deep it goes
Demonstrates pathlib operations and filename attributes through examples, including a four-step file-moving procedure.
Examples
Uses subject data files to demonstrate cross-platform path construction, file moves, deletion, and pairing .dat files with .config files.
What you can do after
Apply pathlib to create directories, build paths, move or delete files, and inspect filename-related attributes.
How it connects
Connects file paths with pathlib, directory management, file moving, glob patterns, and file metadata.

Also explained in

Compare how 2 books explain file path →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.