Search code examples
pythonfor-loopglobfile-renameenumerate

rename multiple files using glob with Python (file already exists)


I trying to rename multiple files inside a directory with Python, but the count inside for loop never update, so I get a "file already exists" error.

How can I get an updated variable (i) so that the name of the file is never repeated?

def change_name():

    for i, filename in enumerate(glob.glob(current_dir + '\packettest.txt')):
        os.rename(filename, os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' ))
        i = i + 1

This is the error that I get:

os.rename(filename, os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' ))
WindowsError: [Error 183] Cannot create a file when that file already exists

EDIT:

Thanks to your comments, I understand what enumerate does, but the problem persist, i still equal 0. This is my full code:

import os.path
import sys
import glob
import time
current_dir = os.getcwd()
file_path = current_dir + "\packettest.txt"

#def main():

def change_name():

    for i, filename in enumerate(glob.glob(current_dir + '\packettest.txt')):
        os.rename(filename, os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' ))

def packet_listener():
    while not os.path.exists(file_path):
        time.sleep(1)
        print "waiting..."

    if os.path.isfile(file_path):
        # read file
        change_name()
        time.sleep(1)
        packet_listener()
        print "OK"    
    else:
        raise ValueError("%s isn't a file!" % file_path)

if __name__ == '__main__':
    packet_listener()

Thanks for advance.

P.S.: sorry for my bad English


Solution

  • Below (avoid incrementing i since enumerate already does it)

    def change_name():
        for i, filename in enumerate(glob.glob(current_dir + '\packettest.txt')):
            os.rename(filename, os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' ))