I need python to write multiple file names, each file name is different from the last. I have an entry in a for loop. Therefore, data files written using the Python program should look like this: data1.txt, data2.txt, data3.txt. How can I do this in Python 3.2? Obviously, a number changes only as a file name.
Alternatively using with
with
for i in range(10): with open('data%i.txt' %i, 'w') as f: f.write('whatever')
withtakes care of closing the file if something goes wrong. This can be especially important if you create files in a for loop,
for i in range(10): f = open("data%d.txt" % i, "w") # write to the file f.close()
I'm not too familiar with Python 3.2, you may need to use the new string formatting as follows: "data{0}.txt".format(i)
"data{0}.txt".format(i)