问题
I need python to write multiple file names, each file name is different than the last. I have it writing in a for loop. Therefore the data files written from the Python program should look like this: data1.txt, data2.txt, data3.txt. How can I do this in Python 3.2? Obviously, the number is the only thing changing as the file name.
回答1:
Alternatively using with
for i in range(10):
with open('data%i.txt' %i, 'w') as f:
f.write('whatever')
with
takes care of closing the file if something goes wrong. This could be especially important if you are creating files in a for loop,
回答2:
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 though, you might need to use the new string formatting like so: "data{0}.txt".format(i)
来源:https://stackoverflow.com/questions/6351007/python-multiple-file-writing-question