Robin Thorben
Robin Thorben

Reputation: 89

Include changing variables into name of output file in Python

I'm new to Python (and programming), so bear with me if I ask really stupid questions :)

So, I want to include variables in the filename of the results. This is what I have so far:

resfile = open("simple.csv","w")
#lots of stuff of no relevance

resfile.close()

In the script I have two variables, minLenght=5000 and minBF=10, but I want to change them and run the script again creating a new file where I can see the number of the variables in the title of the file created, e.g. simple500010 and I want a new file created everytime I run the script with different values for the two variables.

I tried this:

resfile = open("simple" + [str(minLength)] + [str(minBF)].csv,"w")

But that doesn't work.

Any ideas?

Upvotes: 3

Views: 21946

Answers (1)

cdarke
cdarke

Reputation: 44394

Almost there! Dispense with the [ ], which returns a list:

minLength = 5000
minBF = 10

resfile = open("simple" + str(minLength) + str(minBF) + ".csv","w")

resfile.close()

Also, you did not have any quotes around the ".csv".

However, the problem with constructing a string directly into an argument to a function (like open) is that it is a pig to debug. You might find it easier to use a variable to store the filename in first:

filename = "simple" + str(minLength) + str(minBF) + ".csv"
resfile = open(filename,"w")

Now you can experiment with other ways of constructing a string without using + and str() all the time, for example:

filename = "simple%d%d.csv" % (minLength,minBF)
print filename

Upvotes: 12

Related Questions