f = codecs.open('import.txt', 'w', 'utf-8')
for x in list:
string = "Hello"
f.write(string+'\n')
f.close()
For some reason this code does not write newlines to the file, as it would do if I had used the open function instead of codecs.open.
How do I solve this?
codecs.open() does not handle newlines correctly ('U' mode is deprecated):
Underlying encoded files are always opened in binary mode. No automatic conversion of '\n' is done on reading and writing.
Use builtin open() function instead. If you want the same code to work on both Python 2 and 3 from the same source; you could use io.open().
not sure what you are talking about ... also showing you how to have a complete runnable example
>>> import codecs
>>> f = codecs.open('import.txt', 'w', 'utf-8')
>>> f.write("hello\nworld\n")
>>> f.close()
>>> print repr(open("import.txt").read())
'hello\nworld\n'
>>>
based on the comments the real answer is
DONT USE NOTEPAD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With