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?

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? Commented Dec 27, 2017 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 Commented Dec 27, 2017 at 10:25
  • Not a dupe because the answers mentioned here does not work when the list contains string, numbers float simultaneously. Commented Dec 27, 2017 at 10:33
  • some of the answers are for numeric elements too. For example this, this and this Commented Dec 27, 2017 at 11:04

3 Answers 3

2

You've just:

with open('f1.txt', 'w') as f:
    f.write(str(l1))
Sign up to request clarification or add additional context in comments.

2 Comments

@pstatix why downvote though? Its not like this wont work or anything.
@RoadRunner I upvoted to remove. I misread the listing of elements.
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

Comments

-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.

3 Comments

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) :)
@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
Yes, the string representation is wanted. But you get that with str(l1).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.