Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

python - When to open file in binary mode (b)?

I noticed in the docs they always open a CSV file with ‘wb’. Why the ‘b’? I know b stands for binary mode, but when do you use binary mode (I’d guess CSV file is not binary). If relevant I’m writing to the CSV from results from query by arcpy.da.SearchCursor()

EDIT: just noticed according to this answer wb+ is used for writing a binary file. What does including the + do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use 'b' mode, to read/write binary data as is without any transformations such as converting newlines to/from platform-specific values or decoding/encoding text using a character encoding.

csv module is special. csv data is text and therefore the text mode would be expected but csv module uses ' ' by default to terminate rows on all platforms and it always recognizes both ' ' and ' ' as newlines. If you open the corresponding file in the text mode (with universal newlines) then you will get ' ' (corrupted newlines) on Windows (os.linesep == ' ' there). That is why Python 2 docs say that you must use the binary mode. In Python 3, the text mode is used but you should pass newline='' to disable universal newlines mode. You would also want to disable universal newlines if you want to preserve possible newline characters (such as ' ') embedded in fields.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...