1

I have a list l1=['hi','hello',23,1.23].

I want to write the text ['hi','hello',23,1.23] inside a text file, ie, the value of list as it is.

Simple

with open('f1.txt','w') as f:
     f.write(l1)

doesn't work, so I tried this

f=open('f1.txt','w')
l1=map(lambda x:x+',', l1)
f.writelines(l1)
f.close()

But this doesn't work either. It says

TypeError: unsupported operand type(s) for +: 'int' and 'str'

.

How to accomplish this when list contains numbers, alphabets and float?

user78956
  • 23
  • 4
  • You have list `l1=['hi','hello',23,1.23]` and you want to write the text `['hi','hello','welcome']`, but how are these two related? – Anonymous Dec 27 '17 at 10:24
  • 1
    However if you would have done `f.write(str(l1))`, it should have worked in the first code-snippet you shared – Anonymous Dec 27 '17 at 10:25
  • Not a dupe because the answers mentioned [here](https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python) does not work when the list contains string, numbers float simultaneously. – user78956 Dec 27 '17 at 10:33
  • some of the answers are for numeric elements too. For example [this](https://stackoverflow.com/a/899254/2063361), [this](https://stackoverflow.com/a/6791534/2063361) and [this](https://stackoverflow.com/a/32107439/2063361) – Anonymous Dec 27 '17 at 11:04

3 Answers3

2

You've just:

with open('f1.txt', 'w') as f:
    f.write(str(l1))
MihanEntalpo
  • 1,742
  • 1
  • 12
  • 24
0

you can't write the list directly into the file, But first you have to convert your list into the string and then save the string in to the file. I have answered the same question back. you can check it here.

How write a list of list to file

babygame0ver
  • 389
  • 3
  • 16
-1

Use the list's __str__() method.

with open('file.txt', 'w') as f:
    f.write(l1.__str__())

The __str__() method for any object returns the string that print takes; in your case, your formatted list.

  • 2
    why not just `str(l1)`? `.__str__(..)` is a magic function and it is not a good practice to show magic everywhere (specially when it is not required) :) – Anonymous Dec 27 '17 at 10:27
  • @MoinuddinQuadri oh, I was under the impression from >"I want to write the text ['hi','hello','welcome'] inside a text file" that OP wanted the string's representation – Pedro von Hertwig Batista Dec 27 '17 at 10:32
  • Yes, the string representation is wanted. But you get that with `str(l1)`. – Matthias Dec 27 '17 at 10:49