Search code examples
pythonstring-formatting

How to have an integer in a filename (python)


I am making a code that will create textfiles equal to a number they entered, all named after them. So far i have this

name = input("Enter your name")  
num = input("Enter a number")  
x = 0
for i in range(1,num):
   x = x+1
   file = open(name(x) , "w+")
   lines = ("hi" , name)
   file.writelines(lines)
file.close()

but the name 'name(x)" won't work as a variable name, are there any ways of having variable names like x1, x2, x3 ect with an inputted number?


Solution

  • use formatting:

    instead of name(x) you have to format a string:

    "{0}{1}.txt".format(name, x)
    

    the variable name will be placed on the {0} placeholder, the variable x will be placed on the {1} placeholder.

    this means that if name == "Answer" and x = 42, the file name will be Answer42.txt

    the formatting can be in any way you want:

    "File_{1}_{0}_number{1}.txt".format(name, x)
    

    will become: File_42_Answer_number42.txt;

    or for example your line variable could be:

    line = "Welcome {0}, How are you? you have opened {1} file until now!".format(name, x)