[Tutor] Terminating "\M" characters with regard to csv.DictWriter

Peter Otten __peter__ at web.de
Tue Aug 10 02:28:32 EDT 2021


On 10/08/2021 06:37, Cameron Simpson wrote:
> On 09Aug2021 21:03, Alex Kleider <alexkleider at gmail.com> wrote:
>> PS I need to ponder the following a bit more:-)
>>>>> f = open("tmp.csv", "w", newline="")
>>>   >>> csv.writer(f).dialect.lineterminator
>>> '\r\n'
> 
> I'd imagine the empty string looks false, and falls back to the default.

I'm not sure I understand that remark. If you talk about the newline="" 
argument -- "" means no translation, None means "convert '\n' to the 
os-specific line separator", and False is illegal. On windows:

 >>> with open("tmp.txt", "w", newline="") as f: f.write("foo\nbar\r\n")

9
 >>> open("tmp.txt", "rb").read()
b'foo\nbar\r\n'
 >>> with open("tmp.txt", "w", newline=None) as f: f.write("foo\nbar\r\n")

9
 >>> open("tmp.txt", "rb").read()
b'foo\r\nbar\r\r\n'
 >>> with open("tmp.txt", "w", newline=False) as f: f.write("foo\nbar\r\n")

Traceback (most recent call last):
   File "<pyshell#12>", line 1, in <module>
     with open("tmp.txt", "w", newline=False) as f: f.write("foo\nbar\r\n")
TypeError: open() argument 'newline' must be str or None, not bool




More information about the Tutor mailing list