Python readlines() function writing [' and \n to file

1.2k views Asked by At

So I have this code here which I am sure is trivial to my question as it is just question about readlines in general:

        lines = file_in.readlines()
        self.inputText.insert(1.0, lines,)

If I were to read in a text file, it would write like this to a text file

['Example Text'\n']

or something to that nature instead of what we really want which is:

Example Text

How do I avoid this problem?

2

There are 2 answers

1
Bryan Oakley On

readlines returns a list of lines. To insert this into a text widget you can join those items with a newline, like so:

lines = file_in.readlines()
self.inputText.insert("1.0", "\n".join(lines))
0
abarnert On

readlines() gives you a list of lines. When you try to turn a list as a string, it gives you brackets and commas and the repr (the for-a-programmer-representation, rather than the str, the for-an-end-user-representation, which is why you get the quotes and the \n instead of a newline) of each of its elements. That's not what you want.

You could fix it up after the fact, or add each of the lines one by one, but there's a much simpler way: just use read(), which gives you the whole file as one big string:

contents = file_in.read()
self.inputText.insert(1.0, contents,)

On top of being less code, and harder to get wrong, this means you're not making Python waste time splitting the contents up into a bunch of separate lines just so you can put them back together.


As a side note, there's almost never a good reason to call readlines().