使用Python以二进制模式重新打开文件

时间:2015-06-29 18:31:45

标签: python file-io

假设我有一个在模式'r'中打开的文件对象(例如来自默认的android.applicationVariants.all { variant -> variant.outputs.each { output -> renameApk(variant, output) } } def renameApk(variant, output) { def apkPath = output.outputFile.parent def baseName = project.archivesBaseName baseName += "-${variant.buildType.name}" // add version name and version code baseName += "-v${variant.mergedFlavor.versionName}-${variant.mergedFlavor.versionCode}" // if built on jenkins ci, add jenkins build number: def buildNumber = System.getenv('BUILD_NUMBER') if (buildNumber && buildNumber.size() > 0) { baseName += "-b${buildNumber}" } // if the variant will not be zipAligned, specify that if (!output.zipAlign) { baseName += '-unaligned' } // set the output file output.outputFile = new File(apkPath, "${baseName}.apk"); } 调用),但我需要以二进制模式('rb')读取它。

有没有办法直接更改模式,或者我是否需要使用open()之类的东西创建新的文件对象(假设我的文件对象名为open(foo.name, 'rb'))?

编辑:理想情况下,此问题的解决方案应该与平台无关。

1 个答案:

答案 0 :(得分:2)

在Python 2中,你必须打开一个新的文件对象;您无法在已打开的文件上更改文件模式。

您可以使用上一个文件对象执行此操作:

def reopen_binary(fobj):
    mode = fobj.mode
    if 'b' not in mode:
        mode += 'b'
    return open(fobj.name, mode)  # encoding and newline options don't apply

在Python 3中,您可以通过buffered I/O file object

访问基础TextIOBase.buffer attribute
raw_buffered = fobj.buffer

或一直到raw file object,两者都是二进制的:

raw = fobj.buffer.raw

如果您使用io.open() function,则可以在Python 2中使用相同的层次结构。