Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python2与python3中file.read()的行为_Python_Python 3.x_Python 2.7 - Fatal编程技术网

python2与python3中file.read()的行为

python2与python3中file.read()的行为,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我有一些代码是从Python2翻译成Python3的(在我的示例中没有明显的区别,但它已经改变了)。基本上,我的代码读取二进制音频文件。相同的原始音频文件在读取后大小大不相同,我不知道为什么。主要区别在于其中一个程序是在Python3.8中运行的,旧的是2.7 Python 3代码: def __read_file(self, file): try: a_dir = os.path.join(TestContext().accuracy_dir,s

我有一些代码是从Python2翻译成Python3的(在我的示例中没有明显的区别,但它已经改变了)。基本上,我的代码读取二进制音频文件。相同的原始音频文件在读取后大小大不相同,我不知道为什么。主要区别在于其中一个程序是在Python3.8中运行的,旧的是2.7

Python 3代码:

    def __read_file(self, file):
        try:
            a_dir = os.path.join(TestContext().accuracy_dir,self._accuracy,"Audio") if \
                self._accuracy else TestContext().media_dir
            if "http://" in file:
                f = urllib.request.urlopen(file)
                a_buffer = f.read()
            else:
                if False == os.path.isabs(file):
                    file = os.path.join(a_dir, file)
                with open(file, mode='rb') as f:
                    a_buffer = f.read()

       
        except IOError as e:
            raise IOError('I/O error({0}): {1}'.format(e.errno, e.strerror))

        print("AUDIO BUFFER LENGTH", len(a_buffer))
        return a_buffer
Python 3结果:

AUDIO BUFFER LENGTH: 3977
Python 2结果:

AUDIO BUFFER LENGTH: 122400
我的python 2代码完全相同,只是使用了urllib2而不是urllib

另外,Python2方法是正确的方法。我的音频文件应该有那么大。我不知道为什么它突然变小了


非常感谢您的帮助。

除了您的
try
之外的
在哪里?对不起,我添加了它。它从一开始就存在,我一定是在复制和粘贴时出错了。您是使用本地文件还是远程文件进行测试?它是本地文件调用函数的参数值是多少?特别是,
self.\u精度
文件
的值决定了数据源是什么。在这两种环境中,它们很可能是不同的。