Python Forum

Full Version: Ignore Folder
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How to ignore folder in the dir.
It's not a big problem but still, I don't want to rename folder also.

import os

location = input("Enter folder location: ")

def rename(path, name = 'image_0', ext = '.jpg'):
    os.chdir(path)
    x = 1
    for file in os.listdir():
        src = file
        dst = name + str(x) + ext
        os.rename(src, dst)
        x += 1
print("Renamed Successfully")

rename(location)
Maybe something like:

[f for f in os.listdir(os.curdir) if os.path.isfile(f)]
Not sure what you are trying to do.
You can use the recommended scandir() method instead of the old listdir() method
import os
 
 
def rename(path, name='image_0', ext='.jpg'):
    # WARNING: UNSAFE: this function may overwrite existing files
    # for example if image_01.jpg already exists in target directory,
    # it may easily be overwritten.
    os.chdir(path)
    x = 1
    for entry in list(os.scandir()):
        if entry.is_dir():
            continue
        dst = '{}{}{}'.format(name, x, ext)
        os.rename(entry.path, dst)
        x += 1

if __name__ ==  '__main__':
    location = input("Enter folder location: ")
    rename(location)        
    print('Renamed Successfully')