Casting an int to a string in Python

Viewed 179392

I want to be able to generate a number of text files with the names fileX.txt where X is some integer:

for i in range(key):
    filename = "ME" + i + ".txt" //Error here! Can't concat a string and int
    filenum = filename
    filenum = open(filename , 'w')  

Does anyone else know how to do the filename = "ME" + i part so I get a list of files with the names: "ME0.txt" , "ME1.txt" , "ME2.txt" , and etc

6 Answers

Works on Python 3 and Python 2.7

for i in range(50):
    filename = "example{:03d}.txt".format(i)
    print(filename)

Use format {:03d} to have 3 digits with leading 0, it's a great trick to have the files appear in the right order when looking at them in the explorer. Leave brackets empty {} for default formatting.

# output
example000.txt
example001.txt
example002.txt
example003.txt
Related