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()
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With