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')
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, '*'))
.