I was wondering how can i change the name of a file inside a for loop in order to save it with different consecutive names. e.g
for i in range(0, np.max(idx)+1):
vars()['cluster' + str(i)]= [tracks[x] for x in range(len(tracks)) if idx[x] == i]
function_to_write("/Users/George/Desktop/file.bmp", vars()['cluster' + str(i)])
How can i change the FileName in order to be file1, file2 etc ?
You could do it as follows:
"/Users/George/Desktop/file{0}.bmp".format(i+1)
This uses python's string.format(...)
method which replaces the {}
with the specified value.
The {0}
means that the value to replace this will be the 0th argument (1st position) in format(...)
Furthermore, I see you are using vars()
which means you probably have variables stored as cluster1
, cluster2
, cluster3
, ...
This is generally not a good idea and instead, it is recommended that you use a list
.
If you store all your "clusters" in one list called clusters
, you can then instead do:
for i in range(0, np.max(idx)+1):
clusters[i] = [tracks[x] for x in range(len(tracks)) if idx[x] == i]
function_to_write("/Users/George/Desktop/file{0}.bmp".format(i+1), clusters[i])