我一直在搞乱列表并从列表中创建文件。下面的工作正常,但我确信有更好和更清洁的方法来做到这一点。我了解循环的概念,但找不到可以改造以适应我正在做的事情的具体示例。请有人指出我的正确方向,即通过 f.write 代码循环我的项目列表一次,以生成我所追求的文件。
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()