geomiles
geomiles

Reputation: 305

Looping through list in python to create multiple files

I've been messing around with lists and creating files from a list. The below works fine but I'm sure that there is a better and cleaner way for doing this. I understand the concept of a loop but can't find a specific example which I could remodel to fit what I am doing. Please could someone please point me in the right direction of looping my items list through the f.write code only the once, to generate the files that I'm after.

    items = [ "one", "two", "three" ]

    f = open (items[0] + " hello_world.txt", "w")
    f.write("This is my first line of code")
    f.write("\nThis is my second line of code with " + items[0] + " the first item in my list")
    f.write ("\nAnd this is my last line of code")

    f = open (items[1] + " hello_world.txt", "w")
    f.write("This is my first line of code")
    f.write("\nThis is my second line of code with " + items[1] + " the first item in my list")
    f.write ("\nAnd this is my last line of code")

    f = open (items[2] + " hello_world.txt", "w")
    f.write("This is my first line of code")
    f.write("\nThis is my second line of code with " + items[2] + " the first item in my list")
    f.write ("\nAnd this is my last line of code")
    f.close()

Upvotes: 7

Views: 33689

Answers (3)

You should use a for loop

for item in  [ "one", "two", "three" ]:
    f = open (item + " hello_world.txt", "w")
    f.write("This is my first line of code")
    f.write("\nThis is my second line of code with " + item  + " the first item in my list")
    f.write ("\nAnd this is my last line of code")
    f.close()

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239443

You can use a for loop and a with statement like this. The advantage of using with statement is that, you dont have to explicitly close the files or worry about the cases where there is an exception.

items = ["one", "two", "three"]

for item in items:
    with open("{}hello_world.txt".format(item), "w") as f:
        f.write("This is my first line of code")
        f.write("\nThis is my second line of code with {} the first item in my list".format(item))
        f.write("\nAnd this is my last line of code")

Upvotes: 15

Inbar Rose
Inbar Rose

Reputation: 43437

Regular for loop - with some optimizing.

Data:

items = ["one", "two", "three" ]
content = "This is the first line of code\nThis is my second line of code with %s the first item in my list\nAnd this is my last line of code"

Loop:

for item in items:
    with open("%s_hello_world.txt" % item, "w") as f:
        f.write(content % item)

Upvotes: 2

Related Questions