Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing newline with Python codecs.write

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?

like image 557
wasmachien Avatar asked Dec 03 '25 15:12

wasmachien


2 Answers

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().

like image 143
jfs Avatar answered Dec 05 '25 06:12

jfs


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

like image 23
Joran Beasley Avatar answered Dec 05 '25 06:12

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!