【问题标题】:Python - Is it recommended to always open file with 'b' mode?Python - 是否建议始终以“b”模式打开文件?
【发布时间】:2015-04-23 22:45:53
【问题描述】:

所以我有这个简单的python函数:

def ReadFile(FilePath):
    with open(FilePath, 'r') as f:
        FileContent = f.readlines()
    return FileContent

此功能是通用的,用于打开各种文件。但是,当打开的文件是二进制文件时,此功能不会按预期执行。将open() 调用更改为:

with open(FilePath, 'rb') as f:

解决二进制文件的问题(并且似乎在文本文件中也保持有效)

问题:

  1. 是否安全并建议始终使用rb 模式读取文件?
  2. 如果不是,在哪些情况下有害?
  3. 如果不是,如果您不知道您正在使用什么类型的文件,您如何知道使用哪种模式?

更新

FilePath = r'f1.txt'

def ReadFileT(FilePath):
    with open(FilePath, 'r') as f:
        FileContent = f.readlines()
    return FileContent

def ReadFileB(FilePath):
    with open(FilePath, 'rb') as f:
        FileContent = f.readlines()
    return FileContent


with open("Read_r_Write_w", 'w') as f:
    f.writelines(ReadFileT(FilePath))

with open("Read_r_Write_wb", 'wb') as f:
    f.writelines(ReadFileT(FilePath))

with open("Read_b_Write_w", 'w') as f:
    f.writelines(ReadFileB(FilePath))

with open("Read_b_Write_wb", 'wb') as f:
    f.writelines(ReadFileB(FilePath))

f1.txt 在哪里:

line1

line3

文件Read_b_Write_wbRead_r_Write_wbRead_r_Write_w 等同于源f1.txt

文件Read_b_Write_w是:

line1



line3

【问题讨论】:

    标签: python-2.7 file-io binaryfiles


    【解决方案1】:

    在 Python 2.7 教程中: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

    在 Windows 上,附加到模式的 'b' 以二进制模式打开文件,所以 还有像“rb”、“wb”和“r+b”这样的模式。 Windows 上的 Python 区分文本文件和二进制文件;行尾 文本文件中的字符在数据时会自动稍微改变 被读或写。这种对文件数据的幕后修改 对 ASCII 文本文件很好,但它会破坏这样的二进制数据 在 JPEG 或 EXE 文件中。阅读时要非常小心使用二进制模式 并编写此类文件。在 Unix 上,将 'b' 附加到 模式,因此您可以独立于平台使用它来处理所有二进制文件 文件。

    我从中得出的结论是使用“rb”似乎是最佳实践,看起来您遇到了他们警告的问题 - 在 Windows 上打开带有“r”的二进制文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-01
      • 2015-10-07
      • 2011-07-28
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多