Search code examples
pythonlistsubdirectoryos.walk

How to change the file extension in files in a list


I have this code for opening a folder with these directories. Some of them have the extension html but not all of them. How can I change all the files in my three subdirectories that do not have an extension html in .html ?

from os import walk
mypath = ("/directory/path/to/folder")
f = []
for (dirpath,dirnames,filenames) in walk(mypath):
    f.extend(filenames)
    print(f)

Solution

  • If you are on Python 3.4 or higher, consider using pathlib.

    Here is a solution for your problem using that:

    from pathlib import Path
    
    mypath = Path('/directory/path/to/folder')
    
    for f in mypath.iterdir():
        if f.is_file() and not f.suffix:
            f.rename(f.with_suffix('.html'))
    

    If you need to walk down to sub-directories as well, you can use the Path.glob() method to list all directories recursively and then process each file in that directory. Something like this:

    from pathlib import Path
    
    mypath = Path('/directory/path/to/folder')
    
    for dir in mypath.glob('**'):
        for f in dir.iterdir():
            if f.is_file() and not f.suffix:
                f.rename(f.with_suffix('.html'))
    

    And here is one more way to walk down all directories and process all files:

    from pathlib import Path
    
    mypath = Path('/directory/path/to/folder')
    
    for f in mypath.glob('*'):
        if f.is_file() and not f.suffix:
            f.rename(f.with_suffix('.html'))
    

    Using Path.glob() with two asterisks will list all sub-directories and with just one asterisk it will list everything down that path.

    I hope that helps.