thekevinkalis
thekevinkalis

Reputation: 39

Renaming files with python in specific format

I'm trying to rename files in one folder, in the pattern 0001, 0002, 0010, 0100 etc. I'm very very new to python, so sorry for asking something so basic.

I've searched around, and most of the code I come across will rename files (not how I want it) or strip out certain characters. I've also come across code which uses extra modules (glob) which only take me further down the rabbit hole. Most of what I see just makes my head spin; at the moment my skills don't go beyond simple functions, if, when, for, while statements and so on.

I've cobbled together some code, that I (somewhat) understand, but it doesn't work.

import os

dir = os.listdir("D:\\temp\\Wallpapers")

i = 0

for item in dir:
    dst ="000" + str(i) + ".jpg"
    src = item
    dst = item + dst 

    # rename() function will 
    # rename all the files 
    os.rename(src, dst) 
    i += 1

This is the error I get:

Traceback (most recent call last):
  File "rename.py", line 14, in <module>
    os.rename(src, dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '00-Pyatna.jpg' -> '0000.jpg'

Upvotes: 1

Views: 1283

Answers (2)

ivallesp
ivallesp

Reputation: 2212

It doesn't work because you probably are not in the proper directory and you are trying to find those files in the directory you are located right now. You should do it using absolute paths. See the following code

import os

base_path = "D:/temp/Wallpapers"
files = os.listdir(base_path)


for i, fp in enumerate(files):
    dst = os.path.join(base_path, "{0:04d}.jpg".format(i))
    src = os.path.join(base_path, fp) 
    os.rename(src, dst) 

Upvotes: 1

WiseDev
WiseDev

Reputation: 535

Firstly, you can retrieve the maximum number already present in your folder with the following function

import re
def max_counter_in_files(folder):
    files = os.listdir(folder)
    maxnum = '0'
    if files:
        maxnum = max([max(re.findall("[\d]+", file)) for file in files])
    return maxnum

For example, if your folder contains the files

file001.txt
file002.txt
file003.txt

then max_counter_in_files('path/to/your/files') would return 3.

Secondly, you can use that function to increment your next filename when adding new files. for example,

counter = int(self.max_counter_in_files(dest_path))
filename = f"filename{counter+1:04d}.txt"

filename would then be "filename0004.txt".

Upvotes: 0

Related Questions