Python file()函数

Ber*_*rer 2 python compiler-errors file python-3.x

我一直在修改旧代码以使其符合Python 3,并且遇到了这个单独的脚本

"""Utility functions for processing images for delivery to Tesseract"""

import os


def image_to_scratch(im, scratch_image_name):
    """Saves image in memory to scratch file.  .bmp format will be read 
        correctly by Tesseract"""
    im.save(scratch_image_name, dpi=(200, 200))


def retrieve_text(scratch_text_name_root):
    inf = file(scratch_text_name_root + '.txt')
    text = inf.read()
    inf.close()
    return text


def perform_cleanup(scratch_image_name, scratch_text_name_root):
    """Clean up temporary files from disk"""
    for name in (scratch_image_name, scratch_text_name_root + '.txt',
                 "tesseract.log"):
        try:
            os.remove(name)
        except OSError:
            pass
Run Code Online (Sandbox Code Playgroud)

在第二个函数上,retrieve_text第一行失败并显示:

Traceback (most recent call last):
  File ".\anpr.py", line 15, in <module>
    text = image_to_string(Img)
  File "C:\Users\berna\Documents\GitHub\Python-ANPR\pytesser.py", line 35, in image_to_string
    text = util.retrieve_text(scratch_text_name_root)
  File "C:\Users\berna\Documents\GitHub\Python-ANPR\util.py", line 10, in retrieve_text
    inf = file(scratch_text_name_root + '.txt')
NameError: name 'file' is not defined
Run Code Online (Sandbox Code Playgroud)

这是不推荐使用的功能还是另一个问题?我应该用file()类似的东西代替open()吗?

use*_*ica 5

在Python 2中,open并且file几乎是等效的。file是类型,并且open是名称稍友好的函数;两者都使用相同的参数,并且在调用时执行相同的操作,但是file不鼓励调用创建文件,并且尝试使用类型检查isinstance(thing, open)不起作用。

在Python 3中,io模块中的文件实现是默认的,file内置命名空间中的类型已消失。open仍然有效,这是您应该使用的。