4

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

3 回答 3

11

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

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")
于 2013-11-11T10:34:12.637 回答
2

常规 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 item in items:
    with open("%s_hello_world.txt" % item, "w") as f:
        f.write(content % item)
于 2013-11-11T10:36:32.403 回答
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()
于 2013-11-11T10:34:18.937 回答