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?

0

3 Answers 3

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.

2

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']
2
  • str(l) is the Pythonic way - generally double-underscore (dunder) methods aren't called directly. Oct 17, 2020 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, 2020 at 13:15
1

You can try like this:

with open('FILE.txt', 'w+') as f:
    f.write(myList.__str__())
1
  • 1
    str(myList) is the Pythonic way - generally double-underscore (dunder) methods aren't called directly. Oct 17, 2020 at 13:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.