Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through list in python to create multiple files

Tags:

python

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()
like image 829
geomiles Avatar asked Dec 08 '22 11:12

geomiles


1 Answers

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")
like image 161
thefourtheye Avatar answered Dec 11 '22 09:12

thefourtheye