在python中循环列表以创建多个文件

在python中循环列表以创建多个文件,python,Python,我一直在搞乱列表,从列表中创建文件。下面的方法很好,但我相信有更好更干净的方法。我理解循环的概念,但找不到一个具体的例子,我可以重塑,以适应我所做的。请有人告诉我正确的方向,通过f循环我的项目列表。只写一次代码,生成我要的文件 items = [ "one", "two", "three" ] f = open (items[0] + " hello_world.txt", "w") f.write("This is my first line of code")

我一直在搞乱列表,从列表中创建文件。下面的方法很好,但我相信有更好更干净的方法。我理解循环的概念,但找不到一个具体的例子,我可以重塑,以适应我所做的。请有人告诉我正确的方向,通过f循环我的项目列表。只写一次代码,生成我要的文件

    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()

您可以使用
for
循环和这样的语句。使用
with
语句的优点是,您不必显式关闭文件,也不必担心出现异常的情况

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")

您应该使用for循环

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()

常规for循环-带有一些优化

数据:

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"
循环:


这很有效,非常感谢。我猜在那里的某个地方会有一个for语句,但这只是知道把它放在哪里的问题。再次欢呼这和上面的答案一样好,但是我想添加的代码可能更友好一些。Cheers@geomiles语句行的
末尾应该有一个
for item in items:
    with open("%s_hello_world.txt" % item, "w") as f:
        f.write(content % item)