1

Still new to coding and have been searching but no luck in finding what I have done wrong. Trying to make a discord bot read a text file pick a line and send the message but I can't get \n working for line breaks.

if os.path.exists('text.txt'):
    lines = open('text.txt', encoding='utf-8').read().splitlines()
    text = random.choice(lines)
    await client.send_message(member, text)

I have a text file called text.txt that has this inside

testing this now 
testing

but when it sends the message I Don't get the line break. Everything is on the one line.

tripleee
  • 175,061
  • 34
  • 275
  • 318
Justin Jones
  • 15
  • 2
  • 9
  • splitlines() will split with \n as the separator (https://www.tutorialspoint.com/python/string_splitlines.htm) – robert Dec 21 '18 at 22:21
  • 1
    Does your text file have a line break or the two characters `\n`? – Patrick Haugh Dec 21 '18 at 22:33
  • Test file is the two characters '\n' So one line in the txt file is. testing this now \n testing. It sends this message but also sends the \n as text EG. http://prntscr.com/ly45pi – Justin Jones Dec 21 '18 at 22:37
  • 1
    See [Process escape sequences in a string in Python](https://stackoverflow.com/a/4020824/6779307) – Patrick Haugh Dec 22 '18 at 00:36

2 Answers2

0

You literally wrote "\n" to your text file? Well, '\n' is just a combination of symbols '\' and 'n' (two chars), not the '\n' character. It's an another kind of character. It can't be displayed. In order to insert a newline to your file, just use the capabilities of your text editor (Enter).

comonadd
  • 1,822
  • 1
  • 13
  • 23
  • What I'm trying to do is have multiple lines in my text file and to pick a random line for each message. But each message Needs to have a newline in it.If I do it this way Can only have one message not multiple. – Justin Jones Dec 21 '18 at 22:55
-1

This is my first time answer but I hope this helps.

if os.path.exists('text.txt'):
    with open('text.txt', encoding='utf-8','r') as lines:
        #lines now has a list of each line
        text = random.choice(lines)

    await client.send_message(member, text)