循环遍历python中的列表以创建多个文件

时间:2013-11-11 10:32:01

标签: python

我一直在搞乱列表并从列表中创建文件。以下工作正常,但我确信有更好,更清洁的方法。我理解循环的概念,但找不到我可以改造以适应我正在做的事情的具体例子。请有人请指出我正确的方向循环我的项目列表通过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()

3 个答案:

答案 0 :(得分:6)

您可以像这样使用for循环和with语句。使用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")

答案 1 :(得分:2)

定期循环 - 进行一些优化。

数据:

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 item in items:
    with open("%s_hello_world.txt" % item, "w") as f:
        f.write(content % item)

答案 2 :(得分:1)

你应该使用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()