I have the below files in a directory:
Using os.listdir()
I am reading all the files and then saving them in a list. Below is the code:
y = []
files = os.listdir()
for file in files:
if "mb" in file:
file = file.split("-")
loss = file[5]
lossNum = loss.split('.pth')
y.append(round(float(lossNum[0]), 3))
print(y)
In above code, I am reading the file name and then splitting it so that I get the number for ex 8.199
or 6.184
and I am saving them in the list. Below is the output of the list:
[8.2, 6.185, 4.115, 4.425, 3.897, 3.972, 5.672, 6.112, 6.129, 5.382, 4.558, 5.476, 4.526, 4.579]
Values in the above list is not as per the filenames. For ex, value at index 0 and 1 are correct because in file name Epoch-0
and Epoch-1
has the same number but Epoch-2
has number 5.67
but index 2 of list contains 4.11
which is wrong. This is happening because when we do os.listdit()
it is automatically list Epoch-0, Epoch-1, and then Epoch-10, Epoch-11, Epoch-12 instead of Epoch-2, Epoch-3 and so on. How can I correct this issue. Please help Thanks
CodePudding user response:
You could split the data and save it accordingly the "Epoch-number".
An example:
string = 'mb1-ssd-Epoch-5-Loss'
Number = string.split(sep='-')[3]
Output: 5
Take the name of the file. Apply the split function with the seperator and finally choose the right index.
CodePudding user response:
Do this to sort your files in the order shown in image uploaded in your question:
files = os.listdir()
files.sort(key=lambda x: x.split("-")[3])