-2

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?

Senescence
  • 63
  • 1
  • 7

2 Answers2

3

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

abarnert
  • 354,177
  • 51
  • 601
  • 671
0

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))
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685