简体   繁体   中英

How to create multiple files and its contents from a list?

I'm a newbie in Python. I want to make some txt. files and its contents from this, but I see it only works on the first list (listA) which would be in the filename. And the items of it are all made. But the second list (listB) didn't work it only shows the last item ("3"). Please help me.

listA = ["one", "two", "three"]
listB = ["1", "2", "3"]

for item in listA:
  for item2 in listB:
    with open("random{}.txt".format(item), "w") as f:
        f.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
        f.write("\nLorem ipsum dolor sit amet, consectetur {} adipiscing elit.".format(item2))
        f.write("\nLorem ipsum dolor sit amet, consectetur adipiscing elit.")

Move the second for loop inside the with statement.

Your current code is overwriting your file for each item on listB leaving only the last modified version (ie item2 = "3").

for item in listA:
    with open("random{}.txt".format(item), "w") as f:
        for item2 in listB:
            f.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            f.write("\nLorem ipsum dolor sit amet, consectetur {} adipiscing elit.".format(item2))
            f.write("\nLorem ipsum dolor sit amet, consectetur adipiscing elit.")

You could also keep you current code and open the file in append mode ( 'a' ), but this would be inefficient to close the file just to reopen it.

The problem is with the flag you are using. Right now you are using "w" flag to write to a file. This will overwrite the file if it already exist. If you use "a" (appending flag), it solves your problem. It appends to existing files and if the file does not exist it creates it.

with open("random{}.txt".format(item), "a") as f

Also, you can make your code more efficient by moving the inner loop inside the with statement. This way you only open the file once per each outer loop.

listA = ["one", "two", "three"]
listB = ["1", "2", "3"]

for item in listA:
    with open("random{}.txt".format(item), "w") as f:
        for item2 in listB:
            f.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            f.write("\nLorem ipsum dolor sit amet, consectetur {} adipiscing elit.".format(item2))
            f.write("\nLorem ipsum dolor sit amet, consectetur adipiscing elit.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM