write a file from a list with in python

You can write a file from a list in python using the write() method of a file object. Here's an example:

main.py
list_to_write = ["apple", "banana", "orange"]

with open("output.txt", "w") as f:
    for item in list_to_write:
        f.write("%s\n" % item)
144 chars
6 lines

In this example, we have a list list_to_write containing three items. We open a file called "output.txt" in write mode using a context manager. Then, we loop over each item in the list and write it to the file using the write() method. We add a newline character after each item to make sure they are written to separate lines within the file. Finally, we close the file using the context manager.

After running this code, there will be a new file called "output.txt" in the same directory as the script, containing the three items from the list on separate lines.

related categories

gistlibby LogSnag