Many csv file writing tutorials have a mode set to "wb", why?

For example: Writing to a csv file in Python

with open('StockPrice.csv', 'wb') as f:

Why do we need to open the csv file in binary format?

Is this just a habit or is there a use case when a binary is needed for a csv file?

+4
source share
1 answer

When writing output using a module csvin Windows, you must use the mode "wb", because the module csvwill write out the ends of the lines, \r\nregardless of which platform you are working on.

Windows "w", Python , . , "w" csv, \r\r\n, Python csv .

, . , ("rb"), Python \r\n \n, :

import csv

with open("output.csv", "w") as f:
    w = csv.writer(f)
    w.writerow([1,2,3,4])
    w.writerow([5,6,7,8])

with open("output.csv", "rb") as f:
    print repr(f.read())

Windows, :

'1,2,3,4\r\r\n5,6,7,8\r\r\n'
+7

Source: https://habr.com/ru/post/1541814/


All Articles