何时以二进制模式打开文件(二)? [英] When to open file in binary mode (b)?

查看:220
本文介绍了何时以二进制模式打开文件(二)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文档中注意到,他们总是用 WB。为什么'B'?我知道B代表二进制模式,但是什么时候使用二进制模式(我猜CSV文件不是二进制的)。如果相关,我从arcpy.da.SearchCursor()查询结果写入CSV。
$ b

编辑:根据这个答案 wb + 用于编写二进制文件。什么包括 + do?

解决方案

使用文本模式,可以在写入时将'\ n'字符转换为平台特定的表示形式,然后重新读取。



在windows中,这会将换行符从'\ n'修改为'\r\\\
',这会在其他应用程序中打开CSV文件时出现问题/因此,当打开一个二进制文件时,应该在模式值中加上'b'以二进制模式打开文件,这将提高可移植性。在没有这种区别的系统上,添加'b'不起作用。

注意:'w +'会截断文件。

模式'r +','w +'和'a +'打开文件进行更新(读取和写入)。

https://docs.python.org/2/library/functions.html#open


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?

解决方案

File open default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

In windows this will modify the line breaks from '\n' to '\r\n' which will create problem opening the CSV file in other applications/platforms.

Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. On systems that don’t have this distinction, adding the 'b' has no effect.

Note: 'w+' truncates the file.

Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing).

As detailed here: https://docs.python.org/2/library/functions.html#open

这篇关于何时以二进制模式打开文件(二)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆