Skip to content Skip to sidebar Skip to footer

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,

Solution 1:

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

Solution 2:

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()>>>printrepr(open("import.txt").read())
'hello\nworld\n'
>>>

based on the comments the real answer is

DONT USE NOTEPAD

Post a Comment for "Writing Newline With Python Codecs.write"