problem renaming files with os.rename and my counter

Question:

I’m trying to rename a load of files and using a counter which is loaded into the name.

When I run the script the files in the folder get renamed to start at 02, and not 01.

When i print the counter in the loop it starts at 1.
The folder has 68 files in it.
When count I the length of the list containing the file names before the rename i get 70.
After the script is run there is still 68 files in the folder.

Any ideas on what the issue is?

Thanks.

import os

path = 'spanish_pages_photos/'
pathContents = os.listdir(path)

pathContents.sort()
counter = 0
list = []
for i in pathContents:
    counter += 1
    print(counter)
    os.rename(f'{path}{i}', f'{path}photo_0{counter}.jpg')

Asked By: bananatoast

||

Answers:

listdir function lists files and folders. Your path directory has 68 files and 02 folders/(or 02 hidden files). The counter value 1 is set to the first item: a folder/a hidden file, then the counter value 2 is set to the next item: the first .jpg file after sort

Try this instead: list only no hidden files

 import os
    
    path = 'spanish_pages_photos/'
    pathContents = os.listdir(path)
    
    counter = 0
    list = []
    for i in pathContents:
         if (os.path.isfile(i) and (not i.startswith('.'))): # we need files not (folders, hidden files)
             list.append(i)
    list.sort()
    for i in list:
         counter += 1
         print(counter)
         os.rename(f'{path}{i}', f'{path}photo_0{counter}.jpg')
Answered By: root

os.listdir() is about the content of a directory not only files but also directories. Print also i for verification.

I assume your are on an UNIXoide OS and have hidden directories/files. Instead of os.listdir() use glob.glob(os.path.join(path, '*')).

Answered By: Raphael Bossek
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.