azal
azal

Reputation: 1260

Change name in every iteration in Python in order to save

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 ?

Upvotes: 4

Views: 11196

Answers (5)

Cam
Cam

Reputation: 1763

version using f string.

for i in range(0, np.max(idx) + 1):
    filename = f'/Users/George/Desktop/file{i + 1}.bmp'

Upvotes: 0

sshashank124
sshashank124

Reputation: 32197

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])

Upvotes: 3

Irshad Bhat
Irshad Bhat

Reputation: 8709

You can add every i to file name like this:

function_to_write("/Users/George/Desktop/file"+str(i)+".bmp", vars()['cluster' + str(i)])

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107347

you can use format or %s in a list comprehension :

[function_to_write("/Users/George/Desktop/file{}.bmp".format(i), vars()['cluster' + str(i)]) for i in range(1,n)]

Upvotes: 0

MattDMo
MattDMo

Reputation: 102912

for i in range(0, np.max(idx) + 1):
    filename = "file%d.bmp" % i + 1

should do the trick.

Upvotes: 0

Related Questions