Home > Blockchain >  How can I search folders and files to make sure they follow the correct naming convention?
How can I search folders and files to make sure they follow the correct naming convention?

Time:05-25

I need to search a folder, it's files and any following subdirectory to make sure it follows a certain naming convention. If any of the folders/files do not follow it, I would need to print it out.

foo
|
------folder1
|        |
|         -----correctly_named
|
-------foLDER2
          |
          -----also_correct
          ----inCORRECT!file

how would I best do this? I'm thinking a for loop that searches the folder with path os.listdir() but not sure if that would be the best route.

CodePudding user response:

When it comes to file system operations, pathlib module takes the lead.

from pathlib import Path

def CheckName(dir: Path) -> None:
    for item in dir.iterdir():
        # Checking the name here, it may be file or folder...
        # item.name gives a string containing only name, excluding its directory

        if item.is_dir():
            # Checking name of subfolders items recursively...
            CheckName(item)

CodePudding user response:

Your best bet would be to use the os library with the dirlist function to access all the folders and files.

I would implement a recursive function starting in the folder (path) you want to start the analysis from, and enter the function again for each folder you encounter. If it finds a file then analyze if it follows the naming convention.

  • Related