Search code examples
pythonloopsfiledirectory

Name of files is not changed when python script is run


I was creating a simple python script that iterates through files in a directory and changes the names of the files based on a num variable that increases by one after each iteration. Here is the code used, with the directory and files involved.

import os

directory = 'JAN'
num = 1
for filename in os.listdir(directory):
    f = os.path.join(directory, filename)
    new_f = f'JAN-{num}.txt'.format(num=num)
    if os.path.isfile(filename):
        os.rename(filename, new_f)
    num += 1
    print(new_f)
Current Files

├── _JAN
│   ├── first.txt
│   ├── second.txt
│   ├── third.txt
│   └── fourth.txt

Desired Changes to Files

├── _JAN
│   ├── JAN-1.txt
│   ├── JAN-2.txt
│   ├── JAN-3.txt
│   └── JAN-4.txt

I have tried a few iterations and the only output received is each new file name printed to the console with no changes to the file names within the JAN directory. Any help would be much appreciated.


Solution

  • Like the comments say, you need to check for f not filename and you also need to save it to the dir:

    import os
    directory = 'JAN'
    num = 1
    for filename in os.listdir(directory):
        f = os.path.join(directory, filename)
        new_f = os.path.join(directory, f'JAN-{num}.txt'.format(num=num))
        if os.path.isfile(f):
            os.rename(f, new_f)
        num += 1
        print(new_f)
    

    You can also use enumerate instead of num:

    for i, filename in enumerate(os.listdir(directory), 1):
        f = os.path.join(directory, filename)
        new_f = os.path.join(directory, f'JAN-{i}.txt')
        if os.path.isfile(f):
            os.rename(f, new_f)
        print(new_f)