Home > OS >  Nested if loop not working in python when renaming file
Nested if loop not working in python when renaming file

Time:09-17

I am trying to change the file name inside my folder. My file name is "20.1.tif". I want to rename this in "20.1". The second number .1. goes till 7 like 20.7 and the first number is till 280. i tried looping through the files and renaming it but its not looping through the first number. It goes "20.8".And as there is no 20.8 it through file not found error

 import os
    a = 20
    b = 1
    while True:
        old_file = os.path.join("D:\\file\\{}.{}.tif.tif").format(a,b)
        new_file = os.path.join("D:\\file\\{}.{}.tif").format(a,b)
        os.rename(old_file, new_file)
        b  = 1
        if b > 7:
            a  = 1
            if a > 280:
                break

CodePudding user response:

b  = 1
if b > 7:
    a  = 1
    # NOTE Missing b = 1
    b = 1
    if a > 280:
        break

better implementation

import os


# a filename generator
def create_filenames() -> str:
    """this creates filenames one file at a time"""
    for a in range(20, 280):
        for b in range(1, 7):
            yield f"D:\\file\\{a}.{b}.tif.tif"


# list of filenames to go through
old_filenames = [os.path.join(filename) for filename in create_filenames()]

_results = [os.rename(old_file, old_file.replace('.tif.tif', '.tif')) for old_file in old_filenames if os.path.isfile(old_file)]
# basically results contains nothing dont do anything with them


#to print the list of filenames do this
print(*old_filenames)

CodePudding user response:

Since you already know the files you're trying to rename, you could use for loops instead.

Also, check if the file exists before you try to rename it.

import os

for prefix in range(20, 281):
    for suffix in range(1, 8):
        file = f"D:/file/{prefix}.{suffix}.tif.tif"
        if os.path.isfile(file):
            os.rename(file, file[:-4])
  • Related