user10436512
user10436512

Reputation:

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)

Upvotes: 2

Views: 705

Answers (5)

Keiku
Keiku

Reputation: 8803

If you want to rename only a specific suffix, do the following:

from pathlib import Path

path = Path('./dir')

for f in path.iterdir():
    if f.is_file() and f.suffix in ['.txt']:
        f.rename(f.with_suffix('.md'))

Upvotes: 0

accdias
accdias

Reputation: 5372

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.

Upvotes: 2

Nic Wanavit
Nic Wanavit

Reputation: 2683

First, write an image path generator with the following function.

import os

def getimagepath(root_path):
    for root,dirs,filenames in os.walk(root_path):
        for filename in filenames:
            yield(os.path.join(root,filename))

Input your folder path into the function. Then run a for loop checking the name for ending with html, then change the name with os.rename

paths = getimagepath("............................")
for path in paths:
    if not path.endswith('.html'):
         os.rename(path,path+'.html')

Upvotes: 1

Peter Sutton
Peter Sutton

Reputation: 1213

Call this function with your path.

import os
import os.path


def ensure_html_suffix(top):
    for dirpath, _, filenames in os.walk(top):
        for filename in filenames:
            if not filename.endswith('.html'):
                src_path = os.path.join(dirpath, filename)
                os.rename(src_path, f'{src_path}.html')

Upvotes: 1

Nithin
Nithin

Reputation: 1105

ff = []
for (dirpath,dirnames,filenames) in os.walk(mypath):
    for f in filenames:
        if not f.endswith(".html"): #check if filename does not have html ext
            new_name = os.path.join(dirpath,f+".html")
            os.rename(os.path.join(dirpath,f),new_name) #rename the file
            ff.append(f+".html")
        else:
            ff.append(f)
    print(ff)

Upvotes: 0

Related Questions