1

I have a lot of files that need to be saved inside one folder, but the files that need to be saved have the same name except for one part. So, instead of editing one by one, I want to insert variables into similar parts of the names.

Eg:

D = r"c:\users\folder"
f1 = D + r"\apple_table.bin"
f2 = D + r"\apple_chair.bin"

So, I want to replace apple with variable. Like this but my example got an error

A = apple
F1 = D + r"\ A + table.bin"
F2 = D + r"\ A + chair.bin"

In my project, A keeps changing. So, I need to edit them one by one and it is so painful and slows down me.

Michael M.
  • 10,486
  • 9
  • 18
  • 34

1 Answers1

1

Use a list and a for-loop. For instance:

PATH_TO_FOLDER = r"\PATH\TO\FOLDER"
SUFFIX = "table.bin"
list_of_names = ["apple"]
for item in list_of_names:
    with open("{0}{1}{2}".format(PATH_TO_FOLDER, item, SUFFIX), "w+") as f:
        f.write("<what you need to write>")
Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Thanks for your answer,in my example I put two 'f' only which is f1,f2 need to edit. But actually in my work, I need to edit 20fs. So, to implement your answer, I need to have 20 different suffix? – Ahmad Hamizan Nov 25 '22 at 02:54
  • You can use a dictionary to save your suffixes. And call that dictionary accordingly. – Gwendal Delisle Arnold Nov 25 '22 at 19:28