0

Here is the code explaining my problem:

from tkinter import *
import csv

root= Tk()
root.geometry("1080x720")
TextA, TextB = '',''

ListA = [["Unimportant Title"],["This is a sentence","\n I start the first line of the next line","\nHelp me"], ["sublist", "number 2"]]
for element in ListA[1]:
    TextA = TextA + element

ListB = []
with open ('demo.csv', 'r', newline="\n") as t:
    r = csv.reader(t, delimiter='|')
    for lines in r:
        ListB.append(lines)
    t.close
print(ListB)
for element in ListB[1]:
    TextB = TextB + element

label1 = Label(root, font=("Calibri", 14), text=TextA, fg="white", bg="#282828")
label1.place(relx=0.4,rely=0.3)
label2 = Label(root, font=("Calibri", 14), text=TextB, fg="white", bg="#282828")
label2.place(relx=0.4,rely=0.5)

root.mainloop()

And this is the contents of demo.csv:

"Unimportant Title"
"This is a sentence"|"\n I start the first line of the next line"|"\nHelp me"
"sublist"|"number 2"

The problem I am facing is that when the label displays TextA, the \n is recognised as the newline character and I get an output like this, which is exactly what I want:

This is a sentence
I start the first line of the next line
Help me

But when the label displays TextB which is read from the csv file, the \n is not recognised and I do not get the output I desired. Instead I get it like this:

This is a sentence\n I start the first line of the next line\nHelp me

What should I do?

I have tried both removing and keeping the newline="\n" but it did not work...

I know this seems really specific but this is a vital part of the code I am working on. So far I haven't been able to find a solution or rather where to apply that solution.

  • You'll need to transform the *literal text value* of `\n` (two characters, \ followed by n) into the newline character *after* it is read in from the file. The `newline` option does not apply as that is the *literal text* in the file as *part of* a single CSV line. – user2864740 Jan 10 '22 at 04:28
  • On the other hand, in `"foo\nbar"` the \n is an *escape sequence* in a *string literal* that is converted to the newline character by Python *as it parses* the source code. – user2864740 Jan 10 '22 at 04:33

1 Answers1

0

If you look into the output of print(ListB):

[['Unimportant Title'], ['This is a sentence', '\\n I start the first line of the next line', '\\nHelp me'], ['sublist', 'number 2']]

You will find that \n in the file is read as \\n. You need to convert it back to \n:

for element in ListB[1]:
    TextB += element.replace('\\n', '\n')
acw1668
  • 40,144
  • 5
  • 22
  • 34