Skip to content Skip to sidebar Skip to footer

How Can I Create N Number Of Files In Python?

say user gives a number n=3 then I have to create 3 files dynamically. How will I do that? What can be the names of those files. Specifically I want n number of .jpg file created.

Solution 1:

Assuming you have an image stored in some format (maybe base 64 string?) already, you can do something like:

n = raw_input("Number of files: ")
image_list = ... # your logic for the image data here
n = int(n)
for i inrange(n):
    image = open("image" + str(i) + ".jpg", "w")
    image.write(image_list[i])
    image.close()

For clarification, w means write to filename (overwriting its contents). If you want to append to a file instead, use a.

Edit: removed my wrong explanation on +

Solution 2:

num=input("enter no of files to be created:")
items =[]
for i in range(1,(int(num)+1)):
    items.append(i)
for item in items:
    open("%s_file.txt" % item, "a").close()

Post a Comment for "How Can I Create N Number Of Files In Python?"