Skip to content Skip to sidebar Skip to footer

Python Multiple File Writing Question

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 sho

Solution 1:

Alternatively using with

for i inrange(10):
    withopen('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,

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

Post a Comment for "Python Multiple File Writing Question"