0
xadd = open('x.txt', 'w', encoding="utf-8") hha = [ 'j', 'a', 's', 'o', 'n', '\\n', 'b', 'r', 'o', 'w', 'n'] a = ''.join(hha) xadd.write(a) xadd.close() 

File's output is jason\nbrown. I can assume that the problem is with a variable because when I do it normally, without join file has newlines. Can someone explain me why is that not working and give me the solution for this problem?

8
  • 1
    \n is escaped in your list to \\n Commented Jan 24, 2020 at 13:11
  • yes, but a = jason\nbrown and when I just pass it to write, everything works fine Commented Jan 24, 2020 at 13:13
  • So what's the problem? Commented Jan 24, 2020 at 13:14
  • 1
    @Ignesus You have to either manually change it to \n in your list or just do "".join(hha).replace("\\n", "\n") Commented Jan 24, 2020 at 13:15
  • a = jason\nbrown is not valid in Python. Commented Jan 24, 2020 at 13:18

1 Answer 1

2

Simple fix. Your \\n should be \n

xadd = open('x.txt', 'w', encoding="utf-8") hha = [ 'j', 'a', 's', 'o', 'n', '\n', 'b', 'r', 'o', 'w', 'n'] a = ''.join(hha) xadd.write(a) xadd.close() 

Also consider using a context manager when you open files. This will automatically close the file even if an exception occurs and your code doesn't make it to the .close() line.

with open('x.txt', 'w', encoding="utf-8") as xadd: hha = [ 'j', 'a', 's', 'o', 'n', '\n', 'b', 'r', 'o', 'w', 'n'] a = ''.join(hha) xadd.write(a) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the explanation, for a project I can not change \\n manually, so I did "".join(hha).replace("\\n", "\n") thanks to @zamir

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.