1

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?

Morpheus
  • 54
  • 1
  • 12

3 Answers3

4

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.

Booboo
  • 18,421
  • 2
  • 23
  • 40
1

Updated from original answer using list.__str__()

You can achieve this by making use of str() as below.

l = [1, 'this', 'is', 'a', 'list']

with open('example.txt', 'w') as f:
    f.write(str(l))

Contents of example.txt

[1, 'this', 'is', 'a', 'list']
JPI93
  • 1,297
  • 2
  • 10
  • `str(l)` is the Pythonic way - generally double-underscore (dunder) methods aren't called directly. – snakecharmerb Oct 17 '20 at 13:09
  • @snakecharmerb Spot on, much more pythonic. Feel a fool for jumping straight to a dunder! Thanks for pulling me up on that :) Answer updated. – JPI93 Oct 17 '20 at 13:15
1

You can try like this:

with open('FILE.txt', 'w+') as f:
    f.write(myList.__str__())
programmer365
  • 12,641
  • 3
  • 7
  • 28