sorry if the title is a bit vague. I will try to explain it now.
My scenario is the following:
I am reading a cfg-file and receive a dictionary for each section. So, for example:
Config-File:
[General]
parameter1="Param1"
parameter2="Param2"
[FileList]
file001="file1.txt"
file002="file2.txt" ......
Now, let’s focus on the FileList-section, which is saved as a dictionary. In this example, I can access "file1.txt" as test = section["file001"], so test = "file1.txt". Now, when I want to access every file of FileList one after each other, I could try the following:
i = 1
for i in range(1, (number_of_files + 1)):
access_key = str("file_00" + str(i))
print(section[access_key])
Now, this is my current solution and I don’t like that at all. First of all, it looks kind of messy in python, but I will also face problems when more than 9 files are listed in the config.
I could do it like:
i = 1
for i in range(1, (number_of_files + 1)):
if (i <= 9):
access_key = str("file_00" + str(i))
elif (i > 9 and i < 100):
access_key = str("file_0" + str(i))
print(section[access_key])
But I don’t want to start with that because it becomes even worse. So my question is: What would be a proper and relatively clean way to do that? I definitely need the "looped access" because I need to perform some actions with every file.
>Solution :
Use zero padding to generate the file number (for e.g. see this SO question answer: https://stackoverflow.com/a/339013/3775361). That way you don’t have to write the logic of moving through digit rollover yourself—you can use built-in Python functionality to do it for you. If you’re using Python 3 I’d also recommend you try out f-strings (one of the suggested solutions at the link above). They’re awesome!