3

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?

1 Answer 1

12

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.