Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...