Search code examples
pythonlistwritetofile

Writing a whole list AS SUCH to a text file in Python


In python I don't want to write every single element into a file but a whole list as such. That means the text file should look like this for example:

["elem1", "elem2", "elem3"]
["elem1", "elem2", "elem3"]
["elem1", "elem2", "elem3"]

This is one examples to write each element from a list into a text file (Writing a list to a file with Python). But I don't need this, as I said.

Can anyone help me?


Solution

  • Here are three ways:

    import json
    
    
    l = ["elem1", "elem2", "elem3"]
    print(str(l))
    print(repr(l))
    print(json.dumps(l))
    

    Prints:

    ['elem1', 'elem2', 'elem3']
    ['elem1', 'elem2', 'elem3']
    ["elem1", "elem2", "elem3"]
    

    You can, of course, direct your print statement to an output file.