0

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!

3
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by 1337455 10534
1
a = input("Number: ")
b = 2 + a
filename = eval(str(b))
outfile = open('%s' % filename,'w')
outfile.write(b)
0

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

0
>>> 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
0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.