0

(I am using thonny don't know if that is part of the error) I am trying to write to a file but my code,

thing = ["hello", "goodbye", "please", "help"]
with open('file123.txt', 'w') as file321:
    file321.writelines(thing)
    file321.close()

writes hellogoodbyepleasehelp to file123.txt when I want it to write

 hello                                                           
 goodbye                                                                                   
 please                                                                                     
 help

I have tried having the list be thing = ["/nhello", "/ngoodbye", "/nplease", "/nhelp"] but that just made the file be /nhello/ngoodbye/nplease/nhelp

azro
  • 53,056
  • 7
  • 34
  • 70

1 Answers1

1

To use writelines you may have the newline char \n appended for each line like

thing = ["hello\n", "goodbye\n", "please\n", "help\n"]
with open('file123.txt', 'w') as file321:
    file321.writelines(thing)

But the easiest would be to use str.join

thing = ["hello", "goodbye", "please", "help"]
with open('file123.txt', 'w') as file321:
    file321.write("\n".join(thing))
azro
  • 53,056
  • 7
  • 34
  • 70