Search code examples
pythonfor-looplist-comprehension

I'm writing a code to change a file extension


I've got it to where the code outputs the new filenames, but it doesn't change the intended files I want. Here's the code below. What is it that I'm missing.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]

new_filenames = " "

for filename in filenames:
    if filename.endswith(".hpp"):
        new_filename = filenames.replace(".hpp", ".h")
    else:
        new_filenames = filenames

print(new_filenames)  # it prints out the whole list but it doesn't change ".hpp" to ".h" in the new list

Solution

  • In the loop you're assigning to new_filename, which has nothing to do with filenames or new_filenames. If there are any filenames in the list that don't contain .hpp, you just set new_filenames to filenames, which has not been modified.

    Use a list comprehension:

    new_filenames = [filename.replace('.hpp', '.h') for filename in filenames]
    

    There's no need for the if statement. If the filename doesn't contain .hpp it will be copied unchanged to the result.