If I have something like this

a = input("Number: ")
b = 2 + a

How do I make the answer of b the name of a file? Thanks!

a = input("Number: ")
b = 2 + a
filename = eval(str(b))
outfile = open('%s' % filename,'w')
outfile.write(b)

What is eval? And what is "% filename" the percent for? Thanks for the help leet!

>>> a = input("Number: ")
Number: 10
>>> b = 2 + a
>>> b
12
>>> outfile = open(str(b), 'w')
>>> outfile.write("Test line")
>>> outfile.close()
>>> quit()


C:\Python>type 12
Test line

rikxik has the easier way to do it.
But anyways;
1. eval is an in-built python function. works sort of like C pointers. sort of.
2. in Python, %s in a string followed by % variable outside of the string (but in the same expression) places the given variable as text into the string.
so in
outfile = open('%s' % filename,'w')
is the same as
outfile = open(b,'w')
but its a habbit of mine to have a variable serve only 1 purpose in a program so that it can be deleted immediately after it is used.
(with del).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.